Criteria.DISTINCT

编程入门 行业动态 更新时间:2024-10-15 22:26:51
本文介绍了Criteria.DISTINCT_ROOT_ENTITY 与 Projections.distinct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对 Hibernate 还很陌生.我发现我们可以使用以下两种不同的方式获得不同的结果.谁能告诉我它们之间有什么区别?什么时候使用一个?

I am pretty new to Hibernate. I found out that we can get distinct result using following two different ways. Could any one tell me what is the difference between them? When to use one over other?

Projections.distinct(Projections.property("id"));

对比

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

推荐答案

虽然名称相似,但用法不同.

While similar names, the usage is different.

该语句将被翻译成 SQL 语句.它将被传递到数据库引擎并作为 SQL DISTINCT 执行.见:

this statement would be translated into SQL Statement. It will be passed to DB Engine and executed as a SQL DISTINCT. See:

  • 17.9.投影、聚合和分组

所以例如这个例子:

List results = session.createCriteria(Cat.class) .setProjection( Projections.projectionList() .add( Projections.distinct(Projections.property("id")) ) ) .list();

看起来像:

SELECT DISTINCT(cat_id) FROM cat_table

二.criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

此语句在事后执行.返回来自数据库引擎的 SQL 查询并且 Hibernate 迭代结果集以将其转换为我们的实体列表.

II. criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

This statement is executed ex-post. Once the SQL query from DB engine is returned and Hibernate iterates the result set to convert that into list of our entities.

但它总是需要吗?不,大多数情况下不需要.

But is it needed always? NO, mostly this is not needed.

唯一的情况,当我们必须使用它时,如果查询中有关联 - 加入 one-to-many 结束.

The only case, when we MUST to use that, if there is an association in the query - JOINING the one-to-many end.

因为如果我们有一只 cat 和它的两只 kittens,这将返回 两个 行,而 cat 只有 一行:

Because if we do have one cat and its two kittens, this would return two rows, while cat is only one:

SELECT cat.*, kitten.* FROM cat_table as cat INNER JOIN kitten_table kitten ON kitten.cat_id = cat.cat_id

所以,criteriaQuery 末尾的语句:

... // criteriaQuery joining root and some one-to-many .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)

将导致列表中只有一只猫.

would result in a list with only one cat.

更多推荐

Criteria.DISTINCT

本文发布于:2023-10-24 21:17:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525032.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Criteria   DISTINCT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!