Transforming database query result to Map using Transformers and Criteria api

We can use Hibernate Criteria to convert records returned by Hibernate to a Map.

For this, we can set the ResultTransformers in following manner :

Criteria criteria = session.createCriteria(Employee.class);
criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

This converts every record returned to a Map.

If we get the records using criteria.list() and print, they will look like this :


[{this=Employee{id = 2, name = Nicholas Flammel, age = 101}}, 
{this=Employee{id = 3, name = Ram Kumar, age = 34}}, 
{this=Employee{id = 6, name = Bob Thomas, age = 40}}, 
{this=Employee{id = 7, name = Andy Murray, age = 40}}]

Here, every element in the List is represented in Map format, where the key is this and value represents an Employee object.

We can access the Employee objects using Criteria.ROOT_ALIAS as the key as it is same as this.
 
Here is the complete example :

package com.topjavatutorial;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.transform.Transformers;

public class HibernateDemo {

  public static void main(String[] args) {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    SessionFactory factory = configuration.buildSessionFactory();
    Session session = HibernateSessionUtil.getSession();

    Criteria criteria = session.createCriteria(Employee.class);
    criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map> emplList = criteria.list();
    System.out.println(emplList);
    for(Map elem : emplList){
      Employee emp = (Employee) elem.get(Criteria.ROOT_ALIAS);
      System.out.println(emp);
    }
    session.close();
    factory.close();
  }
}


 

Output:


Hibernate: 
    select
        this_.id as id1_0_0_,
        this_.age as age2_0_0_,
        this_.name as name3_0_0_ 
    from
        Employee this_
[{this=Employee{id = 2, name = Nicholas Flammel, age = 101}}, {this=Employee{id = 3, name = Ram Kumar, age = 34}}, {this=Employee{id = 6, name = Bob Thomas, age = 40}}, {this=Employee{id = 7, name = Andy Murray, age = 40}}]

Employee{id = 2, name = Nicholas Flammel, age = 101}
Employee{id = 3, name = Ram Kumar, age = 34}
Employee{id = 6, name = Bob Thomas, age = 40}
Employee{id = 7, name = Andy Murray, age = 40}

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags