session#refresh不使用@ManyToOne和复合键刷新根实体

时间:2018-09-20 12:02:34

标签: java hibernate jpa

我具有以下实体和映射:

@Entity
public class Father {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "father", cascade = CascadeType.ALL)
    private Set<Child> childs = new HashSet<>();

    // getters and setters

}

@Entity
@IdClass(Child.ChildPk.class)
public class Child {

    @Id
    @JoinColumn(name = "father_id")
    @ManyToOne(optional = false)
    private Father father;

    @Id
    @Column(name = "name")
    private String name;

    public Child() {

    }

    // getters and setters

    static class ChildPk implements Serializable {

        private Father father;
        private String name;

        // getters and setters
        // equals and hashcode on both father and name
    }
}

如您所见,我的Child类在其所有成员上都有一个组合键,包括其到@OneToMany的{​​{1}}链接。

我遇到的问题如下: 当我尝试刷新Father实体(Father)时,它没有正确刷新:重新加载了Child,并且父亲也在Child内,但不是根父亲。

我试图在简化的上下文中重现(带有H2和JPA的简单Spring Boot项目,现在由于实体加载的无限循环而出现StackOverflow错误)。

我的映射有问题吗?

这是重现错误的github项目:https://github.com/bpagnier/test-jpa

谢谢! :)

1 个答案:

答案 0 :(得分:1)

有人帮助我找到了一个解决方案:通过删除REFRESH来更改OneToMany的Cascade配置!

之前:

@OneToMany(mappedBy = "father", cascade = CascadeType.ALL)

之后:

@OneToMany(mappedBy = "father", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE})