简体   繁体   English

Hibernate持久化实体意外行为

[英]Hibernate persisting entity unexpected behavior

I have parent and childs relation : 我有亲子关系:

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;
}

And I have created a function to persist the parent with it's childrens: 我创建了一个函数来保留父级的子级:

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();
        }
    }

Since the parent entity beign persisted in one transaction, so the expected behaviour of Hibernate that if something goes wrong while inserting the childrens the parent won't be inserted either, but I got something different ! 由于父实体beign保留在一项事务中,因此Hibernate的预期行为是:如果在插入子代时出错,则也不会插入父代,但是我得到了一些不同的东西!
Hibernate inserted the parent and when the children was not inserted the rollback did not happen! Hibernate插入了父级,而当未插入子级时,回滚没有发生! So I found myself with parent only in the database ! 所以我发现自己只和父母在数据库中!
Is that normal or am I doing something wrong ?! 那是正常的还是我做错了什么?

Try like this: 尝试这样:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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