简体   繁体   中英

Hibernate unidirectional one-to-many: Persist parent from children

These are my classes:

 @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 // ... } 

When I try to persist a Children object (c), the Parent object (p) is not persisted on database:

 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 

How can I do this? I need to do that from ChildrenDAO.

Without having a reverse relationship from Children to Parent, it is not possible that to happen automatically. It is because the no JPA provider has all object graph in its cache, meaning it is very likely that the parent is simply not known to the JPA provider.

So solve the problem you can do one of the things:

  1. Add a reverse relationship from Children to Parent and apply a PERSIST cascading.
  2. Persist the parent manually (by either using the parentDao or directly with EntityManager.persist() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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