【发布时间】:2015-11-01 09:29:52
【问题描述】:
我们有 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;
...
}
【问题讨论】:
-
您如何将
EntityB与EntityA关联起来?请编辑答案以添加代码。如果您使用其构造函数创建 entityB 并传递 entityA,则发布的第一个代码 sn-p 应该可以工作,所以我认为问题与逻辑和事务有关。另一条评论,如果您没有设置正确的entityAId值,您发布的第二个代码将不会保持关系。
标签: java spring hibernate jpa hql