Hibernate单向一对多:来自孩子的持久父母

时间:2013-12-11 15:36:06

标签: hibernate parent one-to-many persist

这些是我的课程:

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

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

当我尝试持久化子对象(c)时,父对象(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那里做到这一点。

1 个答案:

答案 0 :(得分:0)

如果没有从儿童到父母的反向关系,则不可能自动发生。这是因为没有JPA提供程序在其缓存中具有所有对象图,这意味着很可能JPA提供者根本不知道父对象。

所以解决问题你可以做其中一件事:

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