[英]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.