JPA - Preserving a relationship from one to a large

This may be a stupid question, but it eavesdrops on me.

I have a bi-directional attitude of many employees towards vehicles. When I first store an Employee in a database (i.e. He does not have an assigned identifier), I also want his associated Vehicles to be saved.

This currently works fine for me, except that my saved Vehicle object does not receive the associated Employee, and in the database, the Foreign_ employee_id column in the Vehicle table is null.

My question is: is it possible for a vehicle employee to be saved at the same time that the employee is saved? I understand that you must first save the Worker, and then save it. Can JPA do this automatically for me? Or I need to do something like the following:

Vehicle vehicle1 = new Vehicle(); Set<Vehicle> vehicles = new HashSet<Vehicle>(); vehicles.add(vehicle1); Employee newEmployee = new Employee("matt"); newEmployee.setVehicles(vehicles); Employee savedEmployee = employeeDao.persistOrMerge(newEmployee); vehicle1.setAssociatedEmployee(savedEmployee); vehicleDao.persistOrMerge(vehicle1); 

Thank!

Edit: as requested here are my mappings (without all other methods, etc.)

 @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="employee_id") private Long id; @OneToMany(mappedBy="associatedEmployee", cascade=CascadeType.ALL) private Set<Vehicle> vehicles; ... } @Entity public class Vehicle { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="vehicle_id") private Long id; @ManyToOne @JoinColumn(name="employee_id") private Employee associatedEmployee; ... } 

I just realized that I had to have the following method defined in my Employee class:

 public void addVehicle(Vehicle vehicle) { vehicle.setAssociatedEmployee(this); vehicles.add(vehicle); } 

Now the code above will look like this:

 Vehicle vehicle1 = new Vehicle(); Employee newEmployee = new Employee("matt"); newEmployee.addVehicle(vehicle1); Employee savedEmployee = employeeDao.persistOrMerge(newEmployee); 

Much easier and cleaner. Thanks for all your help!

+43
java orm jpa one-to-many
Nov 25 '09 at 9:17
source share
2 answers

You must install an associated employee on the vehicle before continuing with the employee.

 Employee newEmployee = new Employee("matt"); vehicle1.setAssociatedEmployee(newEmployee); vehicles.add(vehicle1); newEmployee.setVehicles(vehicles); Employee savedEmployee = employeeDao.persistOrMerge(newEmployee); 
+29
Nov 25 '09 at 12:03
source share

One way to do this is to set the cascade parameter on the "One" side:

 class Employee { // @OneToMany(cascade = {CascadeType.PERSIST}) private Set<Vehicles> vehicles = new HashSet<Vehicles>(); // } 

this when you call

 Employee savedEmployee = employeeDao.persistOrMerge(newEmployee); 

he will also save vehicles.

+15
Nov 25 '09 at 9:32
source share



All Articles