JPA Hibernate一对多批插入
考虑这种情况:JPA Hibernate一对多批插入,hibernate,jpa,Hibernate,Jpa,考虑这种情况: class Parent { private Integer id; private String name; @oneToMany(mappedBy="father") private List<Child> children; ... ... } class Child { private Integer id; private String name; @M
class Parent {
private Integer id;
private String name;
@oneToMany(mappedBy="father")
private List<Child> children;
... ...
}
class Child {
private Integer id;
private String name;
@ManyToOne (optional="false")
@JoinColumn(name="id")
private Parent father;
........
}
Class MyParentService{
public Parent parentService(List<Child> childList){
em.getTransaction.begin();
Parent parent = new Parent();
parent.setChildren(childList);
em.persist(parent);
em.getTransaction.commit();
}
}
这是正确的吗?有没有更好的方法可以避免再次循环childList?我认为这是一件好事-例如,在单元测试中,您可能不使用hibernate,它可以自动设置“父”,但代码仍然可以工作。使用hibernate时,您有责任保持双向关系双方的一致状态。此外,在保持关系时,Hibernate会查看所属方(没有
mappedBy
的方),因此即使没有optional=false
,代码也不会正确
您可以使用以下方法确保一致性:
class Parent {
...
public void addChild(Child c) {
children.add(c);
c.setParent(this);
}
}
public Parent parentService(List<Child> childList) {
...
for (Child c: childList) {
parent.addChild(c);
}
...
}
类父类{
...
公共无效添加子项(子项c){
添加(c);
c、 setParent(本);
}
}
公共父/母服务(列表子列表){
...
for(子c:子列表){
父母、子女(c);
}
...
}
在这种情况下,可以限制setChildren()
的可见性,以避免错误调用
同样,在与父事务的同一事务中没有级联和持久化子事务,这看起来很奇怪。谢谢!我向两侧添加了cascade={CascadeType.ALL}。我不明白你说的“看起来很奇怪,你没有在与父对象的同一事务中持久化子对象”是什么意思。当我持久化父对象时,它不会自动持久化他和他的集合的所有元素吗??(子项)集合的元素只有在配置级联时才会自动持久化,因此如果没有
cascade
,它看起来很奇怪。
class Parent {
...
public void addChild(Child c) {
children.add(c);
c.setParent(this);
}
}
public Parent parentService(List<Child> childList) {
...
for (Child c: childList) {
parent.addChild(c);
}
...
}