Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setResultTransformer in Criteria

Tags:

What is the use of setResultTransformer method in criteria API? Can someone explain this with a simple example? I read the javadocs but i am not able to understand them clearly.

Regards,

like image 936
user182944 Avatar asked Jun 09 '12 12:06

user182944


People also ask

What is Setresulttransformer in hibernate?

Hibernate's ResultTransformers provide various ways to map the result of your query to different data structures. They were commonly used in Hibernate 4, got deprecated in Hibernate 5 and got replaced by the functional interfaces TupleTransformer and ResultListTransformer in Hibernate 6.

What is criteria Distinct_root_entity?

DISTINCT_ROOT_ENTITY. Each row of results is a distinct instance of the root entity. static String. ROOT_ALIAS. The alias that refers to the "root" entity of the criteria query.


1 Answers

The default ResultTransformer for a Criteria query which does not use setProjections() will be ROOT_ENTITY.

If we have Student in a ManyToMany relationship to Department a query might look like this ...

    Session session = (Session) getEntityManager().getDelegate();     Criteria crit = session.createCriteria(Student.class)         .createAlias('departments', 'department'); 

This query will return duplicates. But set the ResultTransformer as ...

    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); 

Now the results will be distinct when Hibernate marshalls the results. (Or do I mean unmarshalls?)

If you do not want Hibernate to return the query as a List<Student> but prefer to handle the results as a List<Object[]> then

    crit.setResultTransformer(CriteriaSpecification.PROJECTION) 
like image 110
carbontax Avatar answered Sep 28 '22 01:09

carbontax