Not able to fetch child entities using inner join

2019-08-18 05:26发布

Hi I am trying to fetch a parent class Department where I have a clause for employee as well.

In the Employee table I have an indicator is_active. I need to find a department which is having multiple employees where is_active is not 'N'.

I tried using repository.

@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);

The above query is giving me the parent data but when tried to loop through the child entities it is giving me LazyInitializationException on Employee, could not initalize proxy - no session

I have specified the fetchType as lazy on my OneToMany mapping.

The equivalent sql query is as belows.

select t1.*, t2.* from Department t1, Employee t2 where t2.dept_Id = 423 and t1.dept_name='HR' and t1.is_active != 'N'

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-18 06:05

You can try fetch join to eagerly fetch child entities. Query should look next:

  @Query("select t1 from Department t1 inner join fetch t1.employee t2 where t1.deptHead = :deptHead and t1.departmentId = :deptId and t2.isActive != 'N')
查看更多
登录 后发表回答