持久性@OneToMany - @ManyToOne

时间:2014-11-23 14:25:54

标签: java hibernate jpa ejb-3.2

我遇到问题仍然存在以下实体:

@Entity
@Table(name="entityOne")
public class EntityOne implements Serializable  {

   @Id
   @Column(name = "id", nullable = false)
   private Integer id;

   @OneToMany(fetch = FetchType.LAZY, mappedBy="entityOne")
   private List<EntityTwo> entities;

}

@Entity
@Table(name="entityTwo")
public class EntityTwo implements Serializable  {

   @Id
   @Column(name = "id", nullable = false)
   private Integer id;

   @Inject
   @ManyToOne(fetch=FetchType.LAZY)
   @JoinColumn(name="entityOne", referencedColumnName="id")
   private EntityOne entityOne;

}

在EntityOneDAO中:

em.merge(entityOne);

它只是持久存在于EntityOne而不是EntityTwo列表中......如何保留列表?

全部谢谢

3 个答案:

答案 0 :(得分:0)

试试这个:

public class EntityOne implements Serializable  {

   @Id
   @Column(name = "id", nullable = false)
   private Integer id;

   @OneToMany(fetch = FetchType.LAZY, mappedBy="entityOne", 
              cascade = { CascadeType.ALL})
   private List<EntityTwo> entities;

}

@Entity
@Table(name="entityTwo")
public class EntityTwo implements Serializable  {

   @Id
   @Column(name = "id", nullable = false)
   private Integer id;

   @Inject
   @ManyToOne(fetch=FetchType.LAZY)
   @JoinColumn(name="entityOne", referencedColumnName="id")
   private EntityOne entityOne;

}

您可以阅读有关CascadeType的here

<强>编辑。

答案 1 :(得分:0)

您应该明确设置每个entityTwo个对象&#39; entityOne字段。

这样:

entityTwo_1.setEntityOne(entityOne);
entityTwo_2.setEntityOne(entityOne);

entityOne.entities.add(entityTwo_1);
entityOne.entities.add(entityTwo_2);
em.merge(entityOne);

答案 2 :(得分:0)

你需要照顾两者:

  • 传递持久性(使用Cascade)
  • 同步双向关联的两端。

所以EntityOne应该Cascade Persist并合并到EntityTwo:

@OneToMany(fetch = FetchType.LAZY, mappedBy="entityOne", cascade = { CascadeType.PERSIST, CascadeType.MERGE})
private List<EntityTwo> entities = new ArrayList<>();

如您所见,您应该始终初始化集合类以避免不必要的空值检查。

最好在父类中添加以下帮助子项添加实用程序(例如EntityOne)

public void addChild(EntityTwo child) {
    if(child != null) {
        entities.add(child);
        child.setEntityOne(this);
    }
}

然后你可以简单地打电话:

EntityOne entityOne = new EntityOne();
entityOne.setProperty("Some Value");

EntityTwo entityTwo_1 = new EntityTwo();
entityTwo_1.setName("Something"); 

EntityTwo entityTwo_2 = new EntityTwo();
entityTwo_2.setName("Something"); 

entityOne.addChild(entityTwo_1);
entityOne.addChild(entityTwo_2);

entityManager.persist(entityOne);

<强> P.S。

请从EntityTwo类中删除@Inject注释。 Entities are not Components。 当你想插入新的实体时,持久性比合并更有效。