geschema
geschema

Reputation: 2504

Spring Data JPA returning multiple instances of the same object

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

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:

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

```

Upvotes: 3

Views: 2483

Answers (1)

Atmas
Atmas

Reputation: 2393

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.

Upvotes: 3

Related Questions