在Hibernate JPA实体中用另一个列表替换列表是否合法? [英] Is it legal to replace a list by an other one in an Hibernate JPA entity?

查看:111
本文介绍了在Hibernate JPA实体中用另一个列表替换列表是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个Hibernate 4.2 JPA 2.0实体class EntityA,它包含一个@ManyToOne字段List<EntityB> bs.到目前为止,我坚信我不能用new列表替换bs,而是必须使用列表方法clearaddremove.

Assume a Hibernate 4.2 JPA 2.0 entity class EntityA, it contains a @ManyToOne field List<EntityB> bs. Up to now I strongly believed that I must not replace bs by an new List, instead I have to use the list methods clear, add and remove.

今天,我想向一所大学展示,当我用一个新的列表替换列表时,它将引起问题,但是没有什么奇怪的问题,它可以正常工作,数据库和实体已正确更新.现在我很困惑:是否可以将休眠4.x JPA 2替换为持久化实体的集合?

To day I wanted to show a college that it will cause problems when I replace the List with an new one, but nothing strange happed, it worked, the database and the entity was updated correctly. Now I am confused: Is it with the hibernate 4.x JPA 2 allowed to replace a collection of an persisted entity?

由一个站点维护的具有一对多关系的两个实体.

The two enities, with a OneToMany relation ship, maintained by the one-site.

@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));
}

推荐答案

替换列表的内容必须触发数据库中的某些操作时,可能会出现问题.

Problems may happen when replacing contents of a list must trigger some operation in the DB.

例如,有关此情况的一个已知陷阱与具有orphanRemoval = true/CascadeType.DELETE_ORPHAN的列表有关.在这种情况下,替换列表时不会触发孤儿移除.

For example, one known pitfall regarding this scenario is related to lists with orphanRemoval = true/CascadeType.DELETE_ORPHAN. In this case orphan removal won't be triggered when you replace a list.

也许在不同情况下您可能还会遇到其他类似的问题.

Perhaps you may face other kinds of similar problems in different situations as well.

这篇关于在Hibernate JPA实体中用另一个列表替换列表是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆