Criteria API返回的结果集太小

Criteria API返回的结果集太小,第1张

Criteria API返回的结果集太小

通过在Hibernate中打开SQL调试并比较生成的查询,可以很清楚地看到此处发生的情况。

使用一个相当简单的

Sale
Item
一对多映射(希望是不言自明的),这样的
Criteria
基于-的查询如下:

Criteria c = sessionFactory.getCurrentSession().createCriteria(Sale.class);c.createAlias("items", "i");c.add(Restrictions.eq("i.name", "doll"));c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);c.setMaxResults(2);

产生这样的SQL:

select top ? this_.saleId as saleId1_1_, ... from Sale this_ inner join Sale_Item items3_ on this_.saleId=items3_.Sale_saleId inner join Item items1_ on items3_.items_id=items1_.id where items1_.name=?

Query
这样的:

Query q = sessionFactory.getCurrentSession().createQuery("select distinct s from Sale s join s.items as i where i.name=:name");q.setParameter("name", "doll");q.setMaxResults(2);

产生类似:

select top ? distinct hibernated0_.saleId as saleId1_ from Sale hibernated0_ inner join Sale_Item items1_ on hibernated0_.saleId=items1_.Sale_saleId inner join Item hibernated2_ on items1_.items_id=hibernated2_.id where hibernated2_.name=?

请注意第一行中的区别

DISTINCT
)。甲
ResultTransformer
DISTINCT_ROOT_ENTITY
是一个Java类,该处理SQL行的结果
之后
被执行的SQL。因此,当您指定时
maxResults
,它将被用作SQL的行限制;SQL包含对中元素的联接
Collection
,因此您将SQL结果限制为90
个子元素
。一旦应用了
DISTINCT_ROOT_ENTITY
转换器,可能会导致少于20个根元素,这完全取决于在90个连接结果中哪个根元素碰巧排在最前面。


DISTINCT
HQL中的行为实际上有很大不同,因为它实际上使用了SQL
DISTINCT
关键字,该关键字在行限制 之前
应用。因此,它的行为符合您的预期,并解释了两者之间的区别。

从理论上讲,您应该考虑在

setProjection
SQL级别上应用投影-
之类的东西
c.setProjection(Projections.distinct(Projections.rootEntity()))
-但不幸的
Projections.rootEntity()
是不存在,我只是编造了。也许应该!



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5048310.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存