【发布时间】:2018-09-18 17:51:29
【问题描述】:
您好,我正在尝试获取一个父类 Department,其中我也有一个员工子句。
在 Employee 表中,我有一个指标 is_active。 我需要找到一个拥有多名员工且 is_active 不是“N”的部门。
我尝试使用存储库。
@Query("select t1 from Department t1 inner join t1.employee t2 where t1.deptHead = :deptHead and t1.departmentId = :deptId and t2.isActive != 'N')
public Department fetchDepartmentByActiveEmployees(@Param(deptId) Long deptId, @Param(deptHead) String deptHead);
上面的查询给了我父数据,但是当试图循环遍历子实体时,它给了我员工的 LazyInitializationException,无法初始化代理 - 没有会话
我已在 OneToMany 映射中将 fetchType 指定为惰性。
等价的sql查询如下。
select t1.*, t2.* from Department t1, Employee t2 where t2.dept_Id = 423 and t1.dept_name='HR' and t1.is_active != 'N'
【问题讨论】:
-
请在您的查询中使用 fetch
select t1 from Department t1 inner join fetch t1.employee t2 where t1.deptHead = :deptHead and t1.departmentId = :deptId and t2.isActive != 'N' -
@Deedar Ali Brohi 你能具体说明需要的改动吗?我不熟悉 fetch
-
请更新您带注释的@Query
标签: java sql hibernate spring-data-jpa