Hibernate持久化实体意外行为

时间:2016-10-29 09:43:27

标签: java hibernate

我有父母和孩子的关系:

public class Parent{
    private int id;
    @OneToMany(cascade = CascadeType.ALL, mappedBy="parent", orphanRemoval=true)
    private List<Child> childs = new ArrayList<>();
}

public class Child{
    private int id;
    @ManyToOne
    private Parent parent;
}

我已经创建了一个功能,可以让父母与孩子们一起生活:

public void persist(Parent obj) {
        Session session = HibernateUtil.sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.saveOrUpdate(obj);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

由于父实体beign在一个事务中持久存在,所以Hibernate的预期行为如果在插入子节点时出现问题则父节点也不会被插入,但是我得到了不同的东西!
Hibernate插入了父级,当没有插入子级时,回滚没有发生!所以我发现自己只在数据库中与父母联系! 这是正常的还是我做错了什么?!

1 个答案:

答案 0 :(得分:0)

试试这样:

public class Parent{
    @Id
    @Column(name = "id", unique = true, nullable = false)
    private int id;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL,mappedBy="parent", orphanRemoval=true)
    private List<Child> childs = new ArrayList<>();
}

public class Child{
    @Id
    @Column(name = "id", unique = true, nullable = false)
    private int id;

    @Column(name = "parent_id", nullable = false)
    private int parent_id;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "parent_id", insertable = false, updatable = false)
    private Parent parent;
}