我们有 2 个具有 @ManyToOne 关系的实体。
当我们在 @Transactional 方法中创建 EntityB 实例时,entityAId (insertable = false updatable = false) 不会自动更新 - 即使entityA 实例已经被持久化。
有办法解决这个问题吗?我们必须在ctor中手动更新它吗?
@Entity
public class EntityA {
@Id
@GeneratedValue
private Long id;
public EntityA() {
super();
}
...
}
@Entity
public class EntityB {
@Id
@GeneratedValue
private Long id;
@ManyToOne(optional = true, fetch = FetchType.LAZY)
private EntityA entityA;
@Column(name = "entityA_id", insertable = false, updatable = false)
private Long entityAId;
public EntityB() {
super();
}
public EntityB(EntityA entityA) {
super();
this.entityA = EntityA;
}
...
}
编辑:还尝试了以下操作,但在事务中仍然entityAId = null(即使entityA之前已持久化)。
@Entity
public class EntityB {
@Id
@GeneratedValue
private Long id;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "entityA_id", insertable = false, updatable = false)
private EntityA entityA;
@Column(name = "entityA_id")
private Long entityAId;
...
}
最佳答案
Hibernate 不会“即时”填充实体字段(当您更改某些其他字段或类似字段时)。它也不会在持久/刷新时执行此操作(异常(exception)是一些特殊字段,例如 id 和版本)。
从数据库获取实体实例时,将填充不可插入/不可更新的字段。因此,要使这些字段在您对它们映射到的基础列执行更改的同一个事务中由 Hibernate 初始化/刷新,您应该首先刷新 session ,然后执行以下任一操作:
- 清除 session 并重新读取实体;
- 或者,refresh您想要反射(reflect)此类更改的实体。
关于java - JPA 可插入 = false 可更新 = false 创建时未更新 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31903095/