JPA - Persisting a One to Many relationship

后端 未结 2 678
無奈伤痛
無奈伤痛 2020-11-30 00:23

Maybe this is a stupid question but it\'s bugging me.

I have a bi-directional one to many relationship of Employee to Vehicles. When I persist an Employee in the dat

相关标签:
2条回答
  • 2020-11-30 00:51

    You have to set the associatedEmployee on the Vehicle before persisting the Employee.

    Employee newEmployee = new Employee("matt");
    vehicle1.setAssociatedEmployee(newEmployee);
    vehicles.add(vehicle1);
    
    newEmployee.setVehicles(vehicles);
    
    Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
    
    0 讨论(0)
  • 2020-11-30 00:55

    One way to do that is to set the cascade option on you "One" side of relationship:

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

    by this, when you call

    Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
    

    it will save the vehicles too.

    0 讨论(0)
提交回复
热议问题