質問

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()).
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top