Spring data jpa: Entitie gets loaded multiple times

Viewed 96

So I have a relationship between an entity called Building and another entity called building unit. One building can have many building units. So a standard one to many relationships. The problem I'm facing is that every entity of the building unit is loaded 16 times instead of one as intended.

 public class Building {
    @OneToMany(mappedBy = "building",fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JsonManagedReference //<- without this an endless recursion would appear
    private List<buildingUnit> buldingUnits;
    }
public class buildingUnit{
    @ManyToOne()
    @JoinColumn(name = "building_id, nullable = false)
    @JsonBackReference
    private Building building
}

The building also has a relationship with different classes and the building unit has also some more relationships with different classes but I don't think that they will produce this behaviour. I shut mention that in the database everything is stored correctly. Every Building unit is stored once and has a forging-key to a building. So the issue has to come from the code.

The relations of my entities are somewhat like this:

            BuildingUnit    ->
Building ->                    Room -> Wall 
            VentilationZone -> 

building unit and ventilation zone can have different rooms

The Result when I load a building from the DB:

Building:
 buildingUnit: [u1, u1, u1, u1, u1,..., u2, u2, u2, u2,...]  

The DB I'm using is an SQLite DB

3 Answers

I'm not sure if you posted the entire code but I think you are missing the @Entity and @Id. Like the following example:

@Entity
public class Building {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;

...

If it does not fix the problem, it may be worth implementing the equals and hashcode methods.

Maybe because of other collection in your building entity that's getting fetched eagerly ,which will cause a cartesian product due to the double left outer join.

Work around:

I couldn't find a solution to the problem but I found a workaround which removes all duplicates. In the Repository where the buildings are loaded I run a short function which remove all duplicated objects:

private void removeDubplicates(Building building){
    building.setBuildingUnits(
        building.getBuildingUnits.stream()
                                 .distinct()
                                 .collect(Collectors.ToList())                        
    );
}

I think this works because every duplicate in the list is the same object(o1 == o2).

Related