我有一个子实体和两个父实体,每个父实体都有一个子实体列表。如果我通过首先获取Parent_1的子节点然后将该列表分配给Parent_2 hibernate来创建Parent_2的子实体列表,则按照以下代码删除“Parent_1-Child”连接表记录。
Parent_1:
@Entity
@Table
public class Parent_1 extends BusinessObject {
List<Child> children = new ArrayList<Child>();
public Parent_1() {}
public Parent_1(List<Child> children) {
this.children = children;
}
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "parent1_children", joinColumns = @JoinColumn(name = "parent1_id"), inverseJoinColumns = @JoinColumn(name = "child_id"))
@OrderColumn(name = "child_order")
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
Parent_2:
@Entity
@Table
public class Parent_2 extends BusinessObject {
List<Child> children = new ArrayList<Child>();
public Parent_2() {}
public Parent_2(List<Child> children) {
this.children = children;
}
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "parent2_children", joinColumns = @JoinColumn(name = "parent2_id"), inverseJoinColumns = @JoinColumn(name = "child_id"))
@OrderColumn(name = "child_order")
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
儿童:
@Entity
@Table
public class Child extends BusinessObject {
public Child() {}
}
我运行的代码遇到错误:
@Test
public void demoTest() {
Child child_1 = new Child();
Child child_2 = new Child();
save(child_1, child_2);
List<Child> children = new ArrayList<Child>();
children.add(child_1);
children.add(child_2);
Parent_1 parent_1 = new Parent_1(children);
Parent_1 parent_1_1 = new Parent_1(children);
save(parent_1, parent_1_1);
Parent_1 existingParent = dataAccessService.getParentById(new Long(1));
List<Child> newChildren = existingParent.getChildren();
Parent_2 parent_2 = new Parent_2(newChildren);
save(parent_2);
}
这是上次保存时执行的SQL:
Hibernate:
insert
into
Parent_2
(created, deleted, hidden, lastModified, id)
values
(?, ?, ?, ?, ?)
Hibernate:
delete
from
parent1_children
where
parent1_id=?
Hibernate:
insert
into
parent2_children
(parent2_id, child_order, child_id)
values
(?, ?, ?)
Hibernate:
insert
into
parent2_children
(parent2_id, child_order, child_id)
values
(?, ?, ?)
问题在于删除语句。为什么hibernate会执行此操作,我该怎么做才能阻止它发生?
RGDS, 菲尔
注意:BusinessObject只是按照以下方式证明每个表的id:
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
public Long getId(){
return id;
}
答案 0 :(得分:0)
我能给你的最佳答案是它在hibernate上似乎可以正常工作。我重新创建了你的课程。我把注释放在字段而不是方法上,但我认为这没有任何区别。我在Wildfly 9.0.2.Final上将其作为JPA运行。我看到您正在使用Spring
持久性API。我没有尝试重现,但我认为你的问题是可重复的。