Spring Data JPA returning multiple instances of the same object

Viewed 886

In the context of a Spring Boot project using Spring Data JPA, I have defined the following entities:

  • Ent1 contains a list of Ent2 elements
  • Ent2 contains a list of Ent3 elements

When fetching a top-level Ent1 object through a repository, I'm seeing that every Ent2 which has more than one child appears multiple times in the Ent1.ent2 list. For example, an Ent2 with two childs will appear twice.

So instead of getting this:

enter image description here

I'm getting this:

enter image description here

Notes:

  • There are no duplicates in the database
  • If I delete ent3b in the database, the duplicated ent2 disappears

Here's a simplified version of the code:

```java
@Entity
public class Ent1 {
    @OneToMany(mappedBy="parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Ent2> ent2 = new ArrayList<Ent2>();    
}

@Entity
public class Ent2 {
    @ManyToOne
    @JoinColumn(name = "PARENT_ID", nullable = false)
    protected Ent1 parent;

    @OneToMany(mappedBy="parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Ent3> ent3 = new ArrayList<Ent3>();    
}

@Entity
public class Ent3 {
    @ManyToOne
    @JoinColumn(name = "PARENT_ID", nullable = false)
    protected Ent2 parent;
}

```
1 Answers

Solution was to convert Lists into Sets. Lists in JPA require additional data (i.e. an ordering column) to extract a total ordering of elements from the relationship. It can be done but typically the average user only needs Set and it's a reflection of the relationship that most people model.

OP also commented that the previous provider didn't have this requirement so if you were previously using EclipseLink and switching ORM providers this may be a problem for you too.

Related