【发布时间】:2020-12-22 13:46:42
【问题描述】:
我正在编写一个简单的 Spring Data JPA 应用程序。我使用 MySQL 数据库。有两个简单的表:
- 部门
- 员工
每个员工都在某个部门工作 (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();
}
getAll 方法返回一个包含重复部门的列表(每个部门重复的次数与该部门的员工数量一样多)。
问题 1:我是否认为这是一个与 Spring Data JPA 无关但与 Hibernate 相关的功能?
问题2:修复它的最佳方法是什么? (我发现至少有两种方法:1)使用Set<Department> getAll(); 2)在@Query注解中使用"SELECT DISTINCT dep")
【问题讨论】:
标签: java sql spring spring-data-jpa