Selecting certain fields in Hibernate Criteria using Projections

Selecting certain fields in Hibernate Criteria using Projections

This is not a great post but many people will face this issue and the solution is very simple for which many will spend hours of time to find it.

Issue faced by many are selecting certain fields of the table using hibernate criteria, converting array of Objects (Object[]) to respective custom class object, Even after converting the values for the fields will be set to default rather than actual values of the fields.

Take an example :

  Class Person {
    private Integer personid;
    private String personname;
    private String mobilenumber;
    private String permanentaddress;
    private String localaddress;

    public Integer getPersonid(){ }

    public void setPersonid(Integer personid){ }

    public String getPersonname(){ }

    public void setPersonname(String personname){ }

    //Other fields getter/Setter
    
  }

In this example assume that you wish to fetch only personid and personname using hibernate criteria

Fetching only selected fields using Hibernate Criteria






  List persons = null;
  Criteria criteria = sessionObject.createCriteria(Person.class);
		 criteria.setProjection(Projections.projectionList().add(Projections.property("personid")).add(Projections.property("personname")));

 criteria.setResultTransformer(Transformers.aliasToBean(Person.class));
 persons = criteria.list();

Issue : All fields are getting empty/default values after using hibernate projections

This issue is a very difficult to tackle, because hibernate doesn’t through any exception for this but it returns objects filled with default values of fields.

Solution: The solutions is really simple, just use an alias to each field in projections

//See alias personid and personname for both the fields
//Projections.property(“personid”),”personid”) and Projections.property(“personname”),”personname”)

 criteria.setProjection(Projections.projectionList().add(Projections.property("personid"),"personid").add( Projections.property("personname"),"personname"));

 

The above solution doesn’t work for One-To-Many relationship also when there is an aggregation, has-a relationship.

A Wrapper to fetch selected fields using hibernate Projections for One-To-Many relationship

Download the library given below and import it in your project, then define a Response Class like PersonResponse.java, which should be exact replica of Person.java , where it holds all details of a person fetched from database person table.

then just use the below code 

personCriteria.setResultTransformer(new AliasToBeanNestedResultTransformer(PersonResponse.class));

Source Code : AliasToBeanNestedResultTransformer

Thanks to : http://stackoverflow.com/a/25770708/526438

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.