繁体   English   中英

休眠单向一对多:从孩子那里坚持父母

[英]Hibernate unidirectional one-to-many: Persist parent from children

这些是我的课程:

 @Entity public class Parent implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private long id; @OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, fetch = FetchType.EAGER) @JoinColumn(name="parent_id", nullable = false) private List<Children> childrens = new ArrayList<Children>(); // ... } @Entity public class Children implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private long id; // NO BIDIRECTIONAL MAPPING // ... } 

当我尝试持久保存Children对象(c)时,Parent对象(p)未持久保存在数据库中:

 Children c = new Children(); Parent p = new Parent(); p.getChildrens().add(c); childrenDAO.save(c); // Common DAO implementation. It executes a persist on a entity manager 

我怎样才能做到这一点? 我需要从ChildrenDAO做到这一点。

如果没有孩子与父母之间的反向关系,就不可能自动发生。 这是因为no JPA提供程序在其缓存中没有所有对象图,这意味着JPA提供程序很可能不知道父对象。

因此,解决问题可以执行以下操作之一:

  1. 从子级到父级添加反向关系,并应用PERSIST级联。
  2. 手动保持父级(通过使用parentDao或直接与EntityManager.persist() )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM