我定义了两个类,Parent和Child。父母可以有一个孩子的名单。
@Entity
public class Parent {
@Id
@GeneratedValue(...)
@SequenceGenerator(...)
private long id;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false)
private List<Child> children;
public Parent() {
children = new ArrayList<Child>();
}
public void addChild(Child child) { children.add(child); }
}
@Entity
public class Child {
@Id
@GeneratedValue(...)
@SequenceGenerator(...)
private long id;
// The "Child" table in the db also has a not-null "parent_id" column.
}
如果我将一堆子项添加到列表中并保持父项一切正常工作:Hibernate获取序列值,存储父项,然后存储所有子项。
然而,完成所有这些后,它会更新所有子项,将“parent_id”设置为插入中已设置的值!
生成的SQL如下所示:
insert into PARENT (id) values (1)
insert into CHILD (parent_id, id) values (1, 1)
insert into CHILD (parent_id, id) values (1, 2)
insert into CHILD (parent_id, id) values (1, 3)
update CHILD set parent_id = 1 WHERE id = 1
update CHILD set parent_id = 1 WHERE id = 2
update CHILD set parent_id = 1 WHERE id = 3
如果我将此关联设为双向,它可以正常工作,但是我需要在我的子类中引用父类,这是我想要避免的。
存储库是Spring Data JPA存储库:
public interface ParentRepository extends PagingAndSortingRepository<Parent, Long> {}
创建和保存对象的(简化)代码:
Parent parent = new Parent();
parent.addChild(new Child());
parent.addChild(new Child());
repo.save(parent);
有什么建议吗?
答案 0 :(得分:1)
你试过了吗?
@JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false, insertable=false, updatable=false)