我正在休眠一个项目,在Car和CarDriver之间存在@ManyToMany关系。事实是该关系也具有属性,因此,我使用了一个单独的实体,该实体连接到Car和CarDriver,该实体称为CarUsage。
我的问题是,当我保留CarUsage对象时,Car和CarDriver中的CarUsage列表没有被这个新对象填充。
这是我的实体:
汽车:
@Entity
@Table(name = "car")
@Inheritance(strategy = InheritanceType.JOINED)
public class Car extends BaseEntity {
@Column(name = "registration_plate")
private String registrationPlate;
@OneToMany(mappedBy="car")
private List<CarUsage> carUsages;
public String getRegistrationPlate() {
return registrationPlate;
}
public void setRegistrationPlate(String registrationPlate) {
this.registrationPlate = registrationPlate;
}
public List<CarUsage> getCarUsages() {
return carUsages;
}
public void setCarUsages(List<CarUsage> carUsages) {
this.carUsages = carUsages;
}
}
汽车司机
@Entity
@Table(name="car_driver")
public class CarDriver extends BaseEntity {
@OneToMany(mappedBy="carDriver")
private List<CarUsage> carUsages;
public List<CarUsage> getCarUsages() {
return carUsages;
}
public void setCarUsages(List<CarUsage> carUsages) {
this.carUsages = carUsages;
}
}
和我的JoinTable CarUsage:
@Entity
@Table(name = "car_usage")
public class CarUsage extends BaseEntity {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "car_id")
private Car car;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "car_driver_id")
private CarDriver carDriver;
@Column(name = "start_date")
private Date startDate;
@Column(name = "end_date")
private Date endDate;
@Column(name = "active", nullable = false)
private boolean active;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public CarDriver getCarDriver() {
return carDriver;
}
public void setCarDriver(CarDriver carDriver) {
this.carDriver = carDriver;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
当我坚持使用新的CarUsage时,Car和CarDriver中的列表将不会更新。
CarUsage carUsage = carUsageCreator.makeCarUsage(companyCar, carDriver, new Date(), new Date(), true);
carUsageDao.persist(carUsage);
有人知道我做错了吗?
最佳答案
尝试使用JPA /休眠级联:
选择关系的所有者方
汽车> CarUsage> CarDriver或CarDriver> CarUsage>汽车。
如果CarDriver是所有者,则映射应为
@OneToMany(mappedBy="carDriver",cascade = CascadeType.ALL, orphanRemoval = true)
private List<CarUsage> carUsages;
要创建一个新的carUsage关系,您可以创建一个像这样的方法:
public void driveCar(CarDriver carDriver, Car car){
CarUsage carUsage = new CarUsage(carDriver, car, Date()....)
carDriver.getCarUsages().add(carUsage);
car.getCarUsages().add(carUsage);// Just to maintain coherence for the rest of the current transaction
...
}
如果您正在进行交易,此代码将自动保留carUsage实例。 (不再需要carUsageDao.persist(carUsage))。