Criteria.DISTINCT_ROOT_ENTITY 与 Projections.distinct [英] Criteria.DISTINCT_ROOT_ENTITY vs Projections.distinct

查看:35
本文介绍了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:

所以例如这个例子:

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_ROOT_ENTITY 与 Projections.distinct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆