【问题标题】:Not able to fetch child entities using inner join in spring data jpa无法使用弹簧数据 jpa 中的内部联接来获取子实体
【发布时间】: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


【解决方案1】:

您可以尝试 fetch join 以急切地获取子实体。 查询应如下所示:

  @Query("select t1 from Department t1 inner join fetch t1.employee t2 where t1.deptHead = :deptHead and t1.departmentId = :deptId and t2.isActive != 'N')

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 2019-03-17
    • 2014-03-28
    • 2017-11-05
    • 2020-11-11
    • 2021-02-18
    • 2015-07-22
    • 1970-01-01
    • 2021-05-23
    相关资源
    最近更新 更多