无法在 spring 数据 jpa 中使用内部连接获取子实体 [英] Not able to fetch child entities using inner join in spring data jpa

查看:37
本文介绍了无法在 spring 数据 jpa 中使用内部连接获取子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取父类部门,其中我也有一个员工条款.

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

在员工表中,我有一个指标 is_active.我需要找到一个有多个员工的部门,其中 is_active 不是N".

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'.

我尝试使用存储库.

@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,无法初始化代理 - 没有会话

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

我在 OneToMany 映射中将 fetchType 指定为惰性.

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

等效的 sql 查询如下.

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'

推荐答案

您可以尝试 fetch join 来急切地获取子实体.接下来应该查询:

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')

这篇关于无法在 spring 数据 jpa 中使用内部连接获取子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆