66

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

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

目前这对我来说很好,除了我保存的 Vehicle 实体没有自动映射关联的 Employee ,并且在数据库中 Vehicle 表中的 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;

    ...
}

我刚刚意识到我应该在 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);

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

4

2 回答 2

52

在持久化员工之前,您必须在车辆上设置关联员工。

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

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
于 2009-11-25T12:03:22.760 回答
24

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

class Employee {
   // 

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

   //
}

这样,当你打电话时

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

它也将拯救车辆。

于 2009-11-25T09:32:18.647 回答