I’m writing a simple Spring Data JPA application. I use MySQL database. There are two simple tables:
- Department
- Employee
Each employee works in some department (Employee.department_id).
@Entity public class Department { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id private Long id; @Basic(fetch = FetchType.LAZY) @OneToMany(mappedBy = "department") List<Employee> employees; } @Entity public class Employee { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id private Long id; @ManyToOne @JoinColumn private Department department; } @Repository public interface DepartmentRepository extends JpaRepository<Department, Long> { @Query("FROM Department dep JOIN FETCH dep.employees emp WHERE dep = emp.department") List<Department> getAll(); }
The method getAll
returns a list with duplicated departments (each department is repeated as many times as there are employees in this department).
Question 1: Am I rigth that this is a feature related not to Spring Data JPA, but to to Hibernate?
Question 2: What is the best way to fix it? (I found at least two ways: 1) use Set<Department> getAll();
2) use "SELECT DISTINCT dep"
in @Query
annotation)
Advertisement
Answer
FROM Department dep JOIN FETCH dep.employees emp
expression generates native query which returns plain result Department-Employee
. Every Department
will be returned dep.employees.size()
times. This is a JPA-provider expected behavior (Hibernate
in your case).
Using distinct
to get rid of duplicates seems like a good option. Set<Department>
as a query result makes it impossible to get the ordered result.