JPA - 坚持一对多关系

2022-08-31 14:13:18

也许这是一个愚蠢的问题,但它困扰着我。

我有一个双向的一对多员工与车辆的关系。当我第一次将员工保留在数据库中时(即它没有分配的ID),我也希望其关联的车辆被持久化。

目前,这对我来说很好,除了我保存的车辆实体没有自动映射关联的员工,并且在数据库中,车辆表中employee_id外键列为空。

我的问题是,是否有可能让车辆的员工在员工本身被坚持的同时坚持下去?我意识到,员工需要先得救,然后才得救车辆。JPA可以自动为我执行此操作吗?或者我必须执行以下操作:

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);

谢谢!

编辑:根据要求,这是我的映射(没有所有其他方法等)

@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;

    ...
}

我刚刚意识到我应该在我的员工类上定义以下方法:

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

现在上面的代码将如下所示:

Vehicle vehicle1 = new Vehicle();

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

更简单,更干净。谢谢大家的帮助!


答案 1

在保留员工之前,您必须在车辆上设置关联的员工。

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

答案 2

一种方法是在关系的“一”端设置级联选项:

class Employee {
   // 

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

   //
}

通过这个,当你打电话给

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

它也会拯救车辆。


推荐