简体   繁体   English

Hibernate中的单向一对多映射会生成冗余更新

[英]Unidirectional one-to-many mapping in Hibernate generates redundant updates

I have defined two classes, Parent and Child. 我定义了两个类,Parent和Child。 The parent can have a list of children. 父母可以有一个孩子的列表。

@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.
}

If I add a bunch of children to the list and persist the parent everything works as expected: Hibernate gets the sequence values, stores the parent and then stores all the children. 如果我将一堆子项添加到列表中并保持父项一切正常工作:Hibernate获取序列值,存储父项,然后存储所有子项。

However, after doing all this, it updates all the children, setting the "parent_id" to the value it was already set to in the insert! 但是,完成所有这些操作后,它会更新所有子项,将“parent_id”设置为插入中已设置的值!

The generated SQL looks like this: 生成的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

If I make this association bidirectional it works fine, but then I need a reference to the parent in my child class and that's something I want to avoid. 如果我使这个关联双向,它工作正常,但然后我需要在我的子类中引用父,这是我想要避免的。

The repository is a Spring Data JPA repository: 存储库是Spring Data JPA存储库:

public interface ParentRepository extends PagingAndSortingRepository<Parent, Long> {}

The (simplified) code that creates and saves the objects: 创建和保存对象的(简化)代码:

Parent parent = new Parent();
parent.addChild(new Child());
parent.addChild(new Child());
repo.save(parent);

Any suggestions? 有什么建议么?

你有没有尝试过:

@JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false, insertable=false, updatable=false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM