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"));
vs
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Best Answer
While similar names, the usage is different.
I.
Projections.distinct(Projections.property("id"));
this statement would be translated into SQL Statement. It will be passed to DB Engine and executed as a SQL
DISTINCT
. See:so e.g. this example:
would seems like:
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.
Because if we do have one
cat
and its twokittens
, this would return two rows, whilecat
is only one:So, the statement at the end of the
criteriaQuery
:would result in a list with only one cat.