Ral*_*lph 6 java hibernate jpa
假设有一个 Hibernate 4.2 JPA 2.0 实体class EntityA,它包含一个@ManyToOne字段List<EntityB> bs。到目前为止,我坚信我不能bs用newList 替换,而是必须使用 list 方法clear,add和remove。
今天,我想向一所大学展示,当我用新列表替换列表时,它会引起问题,但没有发生任何奇怪的事情,它有效,数据库和实体已正确更新。现在我很困惑:hibernate 4.x JPA 2 是否允许替换持久实体的集合?
这两个实体具有一对多关系,由单一站点维护。
@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
}
Run Code Online (Sandbox Code Playgroud)
测试了一下,没发现问题
@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));
}
Run Code Online (Sandbox Code Playgroud)
当替换列表的内容必须触发数据库中的某些操作时,可能会出现问题。
例如,关于此场景的一个已知陷阱与带有orphanRemoval = true/的列表有关CascadeType.DELETE_ORPHAN。在这种情况下,当您替换列表时,不会触发孤立删除。
也许您在不同情况下也可能面临其他类型的类似问题。
| 归档时间: |
|
| 查看次数: |
1815 次 |
| 最近记录: |