简体   繁体   中英

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 !
Hibernate inserted the parent and when the children was not inserted the rollback did not happen! 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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