JPA - 坚持一对多的关系

时间:2009-11-25 09:17:22

标签: java jpa orm one-to-many

也许这是一个愚蠢的问题,但它让我烦恼。

我有一个双向的员工与车辆的一对多关系。当我第一次在数据库中保留一个Employee(即它没有分配的ID)时,我也希望它的相关Vehicle保持不变。

目前这对我来说很好,除了我保存的Vehicle实体没有自动映射关联的Employee,而在数据库中,Vehicle表中的employee_id外键列为null。

我的问题是,在员工本身被持久化的同时,是否有可能让车辆的员工坚持下去?我意识到需要首先保存员工,然后保存车辆。 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;

    ...
}

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

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

更简单,更清洁。谢谢大家的帮助!

2 个答案:

答案 0 :(得分:35)

在持久化Employee之前,您必须在Vehicle上设置associatedEmployee。

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

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

答案 1 :(得分:17)

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

class Employee {
   // 

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

   //
}

这样,当你打电话

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

它也会拯救车辆。