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

1.9k views Asked by At

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.

1

There are 1 answers

0
V G On BEST ANSWER

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()).