【问题标题】:hibernate fetching duplicate records休眠获取重复记录
【发布时间】:2018-04-17 20:30:54
【问题描述】:

前段时间我在使用内部连接获取子实体时遇到问题。

Not able to fetch child entities using inner join in spring data jpa

我现在面临的问题有点不同。

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

以上代码在使用@Fetch(FetchType.Join)后可以工作

 @Query("select t1 from Department t1 inner join t1.employee t2 where t1.deptHead = :deptHead and t2.isActive != 'N')
    public List<Department> fetchDepartmentByActiveEmployees(@Param(deptId) Long deptId, @Param(deptHead) String deptHead);

仅使用 deptHead 作为查询参数时,我得到重复记录。

我的一个解决方案是使用 Set 进行一对多映射而不是列表。

但如果我这样做,我必须进行很多我想避免的代码更改。 还有其他选择吗?

当我使用 dept_head 查询时,我应该得到一个大小为 2 的列表,而我得到的是大小为 8 的列表。

【问题讨论】:

  • 请将您的代码添加到您的问题中
  • 尝试使用DISTINCT@Query("select DISTINCT t1 from Department t1 inner join fetch t1.employee t2 where t1.deptHead = :deptHead and t1.departmentId = :deptId and t2.isActive != 'N')
  • 它可以作为不同问题的一部分,我在问题中提供的链接。
  • 不过,请将您的代码也添加到此问题中。
  • 如果您仍然遇到问题,请在您的问题中添加示例数据

标签: java hibernate spring-data-jpa


【解决方案1】:

您正在查询 department 表,并且有 4 名员工属于该部门 (dept_head = Ram),因此您从部门表中获取重复记录

dept_head  dept_name    employee_name  
---------  -----------  ---------------
Ram        Electrical   X              
Ram        Electrical   Y              
Ram        Electronics  A              
Ram        Electronics  B  

您可以在查询前使用 distinct 子句 来获取唯一的部门。

即使是普通的 sql 查询也会返回相同的内容。 检查Here

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

正如@hadi j 在评论中所建议的那样。

【讨论】:

  • 我期待 2 条记录,其中不同的只会给我一个
  • 请尝试我在答案中添加的演示,并尝试rextester.com/HBM57592
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多