我有以下结构(OneToOne单向)
@Entity
public class Car {
@Id
@Column(name = ID)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true )
@JoinColumn(name = "DRIVER_ID")
private Driver driver;
// setters and getters and other properties
}
@Entity
public class Driver {
@Id
@Column(name = ID)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// setters and getters and other properties
}
问题是,如果我已经有一个现有的Car,但没有驱动程序,我从数据库中向查询的Car添加了一个驱动程序,则会插入驱动程序(我看到生成的插入查询)。
以下逻辑发生在事务中:
// this is a raw version of the code that gets executed, skipped validation and stuff like that
public void addDriver(long carId, Driver driver) {
entityManager.persist(driver);
Car car = entityManager.find(Car.class, carId);
car.setDriver(driver);
}
交易完成后,我查询了汽车,但是汽车没有连接驱动程序。 知道为什么会这样,以及如何解决这个问题?
答案 0 :(得分:0)
如果您依赖于您的数据库中存在的实体 调用persist(),但在事务提交之前,然后调用 flush()首先。
详情请参阅:
http://blakecaldwell.net/blog/2013/9/3/dont-rely-on-entitymanagerpersist-for-immediate-insert.html
答案 1 :(得分:0)
如果你试试
public void addDriver(long carId, Driver driver) {
Car car = entityManager.find(Car.class, carId);
car.setDriver(driver);
entityManager.merge(car)
}
因为你是级联汽车应插入和链接。