.DISTINCT_ROOT_ENTITY Criteria vs. Projections.distinct

I am new to Hibernate. I found out that we can get great results using two different methods. Can someone tell me what is the difference between the two? When to use one above the other?

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

against

 criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 
+31
hibernate distinct nhibernate hibernate-criteria
Aug 27 '14 at 21:01
source share
2 answers

When using similar names, usage is different.

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

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

those. this example:

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

will look like this:

 SELECT DISTINCT(cat_id) FROM cat_table 

II. criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

This instruction is executed ex-post . After the SQL query returns from the database engine, Hibernate iterates the result set to convert it to a list of our objects.

But is it always necessary? NO, basically it is not required.

The only time we MUST use this if there is an association in the request is the ENTRY at the end of one-to-many .

Since if we have one cat and two kittens , this will return two lines, and cat only :

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

So, the statement at the end of the criteriaQuery :

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

will result in a list with only one cat.

+69
Aug 28 '14 at 5:32
source share

From documents: DISTINCT_ROOT_ENTITY Each row of results is a separate instance of the root object

distinct () selects different properties, in your case by identifier

+3
Aug 27 '14 at 21:05
source share



All Articles