Hibernate Projections

Projections

The Projection class is used in Hibernate to query specific elements. It also provides some build-in aggregate functions like sum, max, min etc.

The Projections class provides several static factory methods for obtaining Projection instances.

After you get a Projection object, add it to your Criteria object with the setProjection() method.
 

Selecting only one column using Projections

Currently, we have following 4 records in the Employee table :

hibernate pagination

If we just want to select only one column in the records, we can do that using following method :

setProjection(Projections object);

For example, below code only selects the names of Employees :

package com.topjavatutorial;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;

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.setProjection(Projections.property("name"));
    List emplList = criteria.list();
    System.out.println(emplList);
    
    session.close();
    factory.close();
  }
}

Output :


Hibernate: 
    select
        this_.name as y0_ 
    from
        Employee this_
[Nicholas Flammel, Ram Kumar, Bob Thomas, Andy Murray]

Use this query style when you want to cut down on network traffic between your application servers and your database servers.

For instance, if your table has a large number of columns, this can slim down your results.

 

Selecting multiple columns using Projections

We can apply more than one projection to a given Criteria object. For this, get a projection list from the projectionList() method on the Projections class.

The ProjectionList object has an add() method that takes a Projection object.

We can then pass the projections list to the setProjection() method on the Criteria object because ProjectionList implements the Projection interface.

If we need to select more than one columns(or in general, add multiple projections), we can use this approach as follows:

  Criteria criteria = session.createCriteria(Employee.class);
  ProjectionList projectionList = Projections.projectionList();
  projectionList.add(Projections.alias(Projections.property("name"),"Employee Name"));
  projectionList.add(Projections.alias(Projections.property("age"),"Employee Age"));
  criteria.setProjection(projectionList);
  criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
  List emplList = criteria.list();
  System.out.println(emplList);

Output:


Hibernate: 
    select
        this_.name as y0_,
        this_.age as y1_ 
    from
        Employee this_
[{Employee Name=Nicholas Flammel, Employee Age=101}, 
{Employee Name=Ram Kumar, Employee Age=34}, 
{Employee Name=Bob Thomas, Employee Age=40}, 
{Employee Name=Andy Murray, Employee Age=40}]

 

Aggregations using Projections

Following aggregate functions are available through the Projections factory class:

• sum(String propertyName): Calculates the sum total of the property values
• avg(String propertyName): Gives the average of a property’s value
• count(String propertyName): Counts the number of times a property occurs
• countDistinct(String propertyName): Counts the number of unique values the property contains
• max(String propertyName): Calculates the maximum value of the property values
• min(String propertyName): Calculates the minimum value of the property values

Here are some examples:

Calculating count of records using Projections

  Criteria criteria = session.createCriteria(Employee.class);
  criteria.setProjection(Projections.rowCount());
  List<Long> results = criteria.list();
  System.out.println(results);

Output :


Hibernate: 
    select
        count(*) as y0_ 
    from
        Employee this_
[4]

 

Calculating sum of values in a column using Projections

  Criteria criteria = session.createCriteria(Employee.class);
  criteria.setProjection(Projections.sum("age"));
  List<Long> results = criteria.list();
  System.out.println(results);

Output :


Hibernate: 
    select
        sum(this_.age) as y0_ 
    from
        Employee this_
[215]

 

Grouping records using Projections

We can use groupProperty projection for grouping records.

Following example, groups data on the age attribute.

  Criteria criteria = session.createCriteria(Employee.class);
  ProjectionList projectionList = Projections.projectionList();
  projectionList.add(Projections.groupProperty("age"));
  criteria.setProjection(projectionList);
  List<Object> results = criteria.list();
  System.out.println(results);

Output :


Hibernate: 
    select
        this_.age as y0_ 
    from
        Employee this_ 
    group by
        this_.age
[34, 40, 101]

 

© 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