session#refresh not refresh root entity with @ManyToOne and composite key

Viewed 42

I have the following entities and mapping :

@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

}

and

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

As you can see, my Child class has a composite key on all its members, including its @OneToMany link to Father.

The problem I encounter is the following : When I try to refresh a Father entity (session.refresh(father)), it is not refreshed correctly : the Child is reloaded, and the Father inside the Child too, but not the root Father.

I tried to reproduce in a simplified context (simple Spring Boot project with H2 and JPA, and now I get a StackOverflow error because of an infinite loop of entity loading).

I there something wrong with my mapping ?

Here is the github project that reproduce the error : https://github.com/bpagnier/test-jpa

Thanks ! :)

1 Answers

Someone helped me find a solution : by changing the Cascade configuration of the OneToMany by removing REFRESH it works !

Before :

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

After :

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

Related