setResultTransformer in Criteria
Asked Answered
A

2

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,

Anticyclone answered 9/6, 2012 at 12:33 Comment(0)
A
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)
Albacore answered 9/6, 2012 at 15:9 Comment(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.Anticyclone
"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.)Albacore
P
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.

Preinstruct answered 22/9, 2014 at 12:49 Comment(2)
Works like a charm. Good tip. ThanksLindley
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"))Eraste

© 2022 - 2024 — McMap. All rights reserved.