JPA - 保持一对多的关系 [英] JPA - Persisting a One to Many relationship
问题描述
也许这是一个愚蠢的问题,但它困扰着我.
Maybe this is a stupid question but it's bugging me.
我有一个员工和车辆的双向一对多关系.当我第一次将 Employee 持久化到数据库中时(即它没有分配的 ID),我也希望它的关联车辆被持久化.
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.
目前这对我来说很好用,除了我保存的 Vehicle 实体没有自动获取关联的 Employee 映射,并且在数据库中,Vehicle 表中的 employee_id 外键列为空.
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.
我的问题是,是否有可能在保留 Employee 本身的同时保留 Vehicle 的雇员?我意识到需要先保存 Employee ,然后再保存 Vehicle .JPA 可以为我自动执行此操作吗?或者我是否必须执行以下操作:
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:
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);
谢谢!
根据要求,这是我的映射(不包括所有其他方法等)
As requested, here's my mappings (without all the 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;
...
}
我刚刚意识到我应该在我的 Employee 类中定义以下方法:
I just realised I should have had the following method defined on 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 simpler and cleaner. Thanks for your help everyone!
推荐答案
在持久化 Employee 之前,您必须在 Vehicle 上设置相关的Employee.
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);
这篇关于JPA - 保持一对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!