Note that there are some explanatory texts on larger screens.

plurals
  1. POJPA - Persisting a One to Many relationship
    primarykey
    data
    text
    <p>Maybe this is a stupid question but it's bugging me.</p> <p>I have a bi-directional one to many relationship of Employee to Vehicles. When I persist an Employee in the database for the first time (i.e. it has no assigned ID) I also want its associated Vehicles to be persisted. </p> <p>This works fine for me at the moment, except that my saved Vehicle entity is not getting the associated Employee mapped automatically, and in the database the employee_id foreign key column in the Vehicle table is null.</p> <p>My question is, is it possible to have the Vehicle's employee persisted at the same time the Employee itself is being persisted? I realise that the Employee would need to be saved first, then the Vehicle saved afterwards. Can JPA do this automatically for me? Or do I have to do something like the following:</p> <pre><code>Vehicle vehicle1 = new Vehicle(); Set&lt;Vehicle&gt; vehicles = new HashSet&lt;Vehicle&gt;(); vehicles.add(vehicle1); Employee newEmployee = new Employee("matt"); newEmployee.setVehicles(vehicles); Employee savedEmployee = employeeDao.persistOrMerge(newEmployee); vehicle1.setAssociatedEmployee(savedEmployee); vehicleDao.persistOrMerge(vehicle1); </code></pre> <p>Thanks!</p> <p>Edit: As requested, here's my mappings (without all the other methods etc.)</p> <pre><code>@Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="employee_id") private Long id; @OneToMany(mappedBy="associatedEmployee", cascade=CascadeType.ALL) private Set&lt;Vehicle&gt; 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; ... } </code></pre> <p>I just realised I should have had the following method defined on my Employee class:</p> <pre><code>public void addVehicle(Vehicle vehicle) { vehicle.setAssociatedEmployee(this); vehicles.add(vehicle); } </code></pre> <p>Now the code above will look like this:</p> <pre><code>Vehicle vehicle1 = new Vehicle(); Employee newEmployee = new Employee("matt"); newEmployee.addVehicle(vehicle1); Employee savedEmployee = employeeDao.persistOrMerge(newEmployee); </code></pre> <p>Much simpler and cleaner. Thanks for your help everyone!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload