问题描述
我有2个一对多关系的类和一个有点奇怪的HQL查询.即使我已经阅读了一些已发布的问题,对我来说也不清楚.
I have 2 classes in a one-to-many relationship and a HQL query that is a bit strange. Even if I have read some questions already posted, it does not seem clear to me.
Class Department{
@OneToMany(fetch=FetchType.EAGER, mappedBy="department")
Set<Employee> employees;
}
Class Employee{
@ManyToOne
@JoinColumn(name="id_department")
Department department;
}
当我使用以下查询时,我得到重复的Department对象:
When I use the following query I get duplicates Department objects:
session.createQuery("select dep from Department as dep left join dep.employees");
因此,我必须使用与众不同的内容:
Thus, I have to use distinct:
session.createQuery("select distinct dep from Department as dep left join dep.employees");
此行为是预期的吗?与SQL进行比较,我认为这很不正常.
Is this behaviour an expected one? I consider this unusual, as comparing it with SQL.
推荐答案
此问题在:
List result = session.createCriteria(Order.class)
.setFetchMode("lineItems", FetchMode.JOIN)
.list();
<class name="Order">
<set name="lineItems" fetch="join">
...
</class>
List result = session.createCriteria(Order.class)
.list();
List result = session.createQuery("select o from Order o left join fetch o.lineItems").list();
SELECT o.*, l.* from ORDER o LEFT OUTER JOIN LINE_ITEMS l ON o.ID = l.ORDER_ID
Collection result = new LinkedHashSet( session.create*(...).list() );
LinkedHashSet过滤掉重复的引用(这是一个集合),然后 它保留插入顺序(结果中元素的顺序).那 太容易了,所以您可以在许多不同且更困难的地方完成 方式:
A LinkedHashSet filteres out duplicate references (it's a set) and it preserves insertion order (order of elements in your result). That was too easy, so you can do it in many different and more difficult ways:
List result = session.createCriteria(Order.class)
.setFetchMode("lineItems", FetchMode.JOIN)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
<class name="Order">
...
<set name="lineItems" fetch="join">
List result = session.createCriteria(Order.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
List result = session.createQuery("select o from Order o left join fetch o.lineItems")
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) // Yes, really!
.list();
List result = session.createQuery("select distinct o from Order o left join fetch o.lineItems").list();
这篇关于一对多关系无需使用"distinct"即可获得重复的对象.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!