24

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,

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
user182944
  • 7,897
  • 33
  • 108
  • 174

2 Answers2

15

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)
carbontax
  • 2,164
  • 23
  • 37
  • 2
    From the doc, i can see this term for ROOT_ALIAS:The alias that refers to the "root" entity of the criteria query. What does the term "root" stands for in this case? I am not able to understand what does root refers in this case. Please explain. – user182944 Jun 09 '12 at 15:44
  • 2
    "root" stands for whatever class you used when creating your Criteria instance. In my example the root is Student. So results will be returned by a call to crit.list() as a List of Student objects. Unless you ask for a ResultTransformation as PROJECTION, in which case it will be a List of Object objects. (Also, I am editing my original example to remove the Restriction so that the query would return duplicates.) – carbontax Jun 09 '12 at 17:03
8

Simply: when you are doing the Criteria: you want the resultset to be into particular object the you can use it like:eg:

 .setResultTransformer(Transformers.aliasToBean(Employee.class));

Employee should match the ResultSet Entity.

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
Appesh
  • 374
  • 4
  • 6
  • Works like a charm. Good tip. Thanks –  Jun 27 '17 at 14:42
  • Note that you need to add alias to each column/property. So you have to use `Projections.alias` e.g.: `.add(Projections.alias(Projections.property("name"), "name"))` – Nux Dec 19 '21 at 23:23