Reputation: 5749
I am using Spring Boot 2 with JPA and Hibernate.
In the first entity, I have a one to many relation:
@Entity
public class Factories{
@Id
@SequenceGenerator(name = "factories_id_seq", sequenceName = "factories_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "factories_id_seq")
private Integer id;
@OneToMany(mappedBy = "factory", cascade = CascadeType.ALL, orphanRemoval = true)
private final List<Machines> machines = new ArrayList<>();
...
}
In the other one, I have a many to one relationship:
@Entity
public class Machines {
@Id
@SequenceGenerator(name = "machines_id_seq", sequenceName = "machines_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "machines_id_seq")
private Integer id;
@ManyToOne
@JoinColumn(name = "factories_id")
private Factories factory;
...
}
I have 3 factories and each one has one machine except one which has two.
When I run this query:
@Query(value= "SELECT f from Factories f JOIN FETCH f.machines m JOIN FETCH f.cities")
public List<Factories> findAllWithMachine();
I get 4 factories (with correct machines child).... Two of them are the same.
I was expecting to get only 3.
Is there something I am doing wrong?
Upvotes: 0
Views: 335
Reputation: 30319
Just add 'distinct' to your query:
@Query("select distinct f from Factories f join fetch f.machines")
public List<Factories> findAllWithMachine();
Another variant is to override findAll
method and use EntityGraph
annotation:
@EntityGraph(attributePaths = "machines")
@Override
List<Factories> findAll();
There is a bug in Spring Data JPA, see my bug report DATAJPA-1299 and example repo.
Upvotes: 1
Reputation: 667
I'm guessing that your query retrieves all factories which have a machine, and since one of them actually has two machines, for each of these two machines the factory is going to be retrieved over again.
If this is not the required behaviour, you could add the DISTINCT
clause to your query, as a hint that you do not wish to see duplicates in your query results.
May I also suggest that you name your entities Factory
and Machine
and not in the plural form, as a List<Factory>
is what translates to the plural already.
Upvotes: 1