坚持一对多的关系

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

我有一个双向的对许多员工对车辆的关系。当我第一次在数据库中持久化一个 Employee (即它没有指定的 ID)时,我也希望它的相关车辆被持久化。

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

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

121004 次浏览

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

class Employee {
//


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


//
}

当你打电话的时候

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

这也将节省车辆。

在持久化 Employee 之前,必须在汽车上设置 AssociatedEmployee。

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


newEmployee.setVehicles(vehicles);


Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);