簡體   English   中英

Hibernate持久化實體意外行為

[英]Hibernate persisting entity unexpected behavior

我有親子關系:

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插入了父級,而當未插入子級時,回滾沒有發生! 所以我發現自己只和父母在數據庫中!
那是正常的還是我做錯了什么?

嘗試這樣:

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