java OneToMany关系在不使用“distinct”的情况下获取重复对象。为什么?
我有两个一对多关系类和一个有点奇怪的HQL查询。即使我读过一些已经贴出的问题,我也不清楚
Class Department{
@OneToMany(fetch=FetchType.EAGER, mappedBy="department")
Set<Employee> employees;
}
Class Employee{
@ManyToOne
@JoinColumn(name="id_department")
Department department;
}
使用以下查询时,我会得到重复的部门对象:
session.createQuery("select dep from Department as dep left join dep.employees");
因此,我必须使用不同的:
session.createQuery("select distinct dep from Department as dep left join dep.employees");
这种行为是预期的吗?我认为这是不寻常的,因为它与SQL相比。p>
# 1 楼答案
我从弗拉德·米哈尔恰先生那里学到了一个很好的建议。有关更多提示: https://vladmihalcea.com/tutorials/hibernate/
# 2 楼答案
使用结果转换器
Criteria.DISTINCT_ROOT_ENTITY
:# 3 楼答案
这个问题在Hibernate FAQ上有详细的解释: