假设一个 Hibernate 4.2 JPA 2.0 实体class EntityA
,它包含一个@ManyToOne
字段List<EntityB> bs
。到目前为止,我坚信我不能用 List 替换bs
,new
而必须使用 list 方法clear
,add
和remove
.
今天,我想向一所大学展示,当我用新列表替换列表时,它会导致问题,但没有发生什么奇怪的事情,它起作用了,数据库和实体已正确更新。现在我很困惑:是否允许使用 hibernate 4.x JPA 2 替换持久实体的集合?
这两个实体具有 OneToMany 关系,由一个站点维护。
@Entity
public class EntityA {
@Id long id;
@OneToMany public List<EntityB>bs;
}
@Entity
public class EntityB {
@Id long id;
hashCode and equals based on id
}
测试了一下,没发现问题
@Test
@Transactional
public testReplaceSet {
//given: a persistent entity a that contains a persistent entity b1
EntityA a = this.entityManager.persist(new EntityA());
EntityB b1 = this.entityManager.persist(new EntityB());
a.bs = new ArrayList();
a.bs = b1;
this.entityManager.flush();
//when: assining a NEW List with an new persistent Entity b2
EntityB b2 = this.entityManager.persist(new EntityB());
a.bs = new ArrayList();
a.bs = b2;
long aId = a.id;
this.entityManager.flush();
this.entityManager.clear();
//then: the collection is correct stored
EntityA AReloaded = this.entityManager.find(EntityA.class, aId);
//here I expected the failure, but there was no!
assertEquals(b2, AReloaded.bs.get(0));
}