Hibernate Projection with Example

By | 2018-09-27T09:16:29+00:00 May 28th, 2016|Hibernate|2 Comments

In this tutorials, we are going to learn about Hibernate Projection with a simple example. As we already discussed in the previous tutorial Hibernate Criteria, If we want to read a partial entity from database, hibernate has provided us Projection interface. This is the tutorial, which provides you a complete picture on Hibernate Projection.

Bullet points about Hibernate Projection :

  • Projection is an interface in Hibernate, which is coming from org.hibernate.criterion package.
  • Projection can be applied on Criteria query.
  • Projection is an Object Oriented Representation of query result set projection in a criteria query.
  • To read partial entity, we need a Projection object for each property.
  • If we want to read more than one property from database, then we need to add Projection objects to ProjectionList and then we need to set ProjectionList object to Criteria.

Simple Hibernate Projection Example :

Criteria criteria = session.createCriteria(Employee.class); 
Projection projection = Projections.property("employeeName"); 
criteria.setProjection(projection); 
List list = criteria.list();

In the above example, we applied Projection on employeeName : Here we would get only one property employeeName from database.

This is some thing like “select ename from emp” in SQL.

Multiple Hibernate Projection Example :

If we want to read more than 1 column (employeeName, salary) with projections, first of all we should prepare all projections and bind all projections into a single ProjectionList like below.

Criteria criteria = session.createCriteria(Employee.class); 
Projection projection = Projections.property("salary"); 
Projection projection2 = Projections.property("departmentId"); 
Projection projection3 = Projections.property("employeeName"); 
ProjectionList pList = Projections.projectionList(); 
pList.add(projection); 
pList.add(projection2); 
pList.add(projection3); 
criteria.setProjection(pList); 
List list = criteria.list();

In the above, we are getting the salary, department id and employee name from database. This is some thing like “select sal,deptid,ename from emp” in SQL. Since those are multiple projections, first we need to add all projections to ProjectionList object and then add ProjectionList object to criteria object.

Complete Example for Hibernate Projection :

Create Employee Pojo Class : Employee.class

Employee.java
package com.otp.hibernate.pojo;

public class Employee {
    private int employeeId;
    private String employeeName;
    private int departmentId;
    private int salary;

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public int getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(int departmentId) {
        this.departmentId = departmentId;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [employeeId=" + employeeId + ", employeeName="
                + employeeName + ", departmentId=" + departmentId + ", salary="
                + salary + "]";
    }   

}

Hibernate mapping file :

employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.otp.hibernate.pojo.Employee" table="employee"
    schema="onlinetutorialspoint">
    <id name="employeeId" column="id">
      <generator class="increment" />
    </id>
    <property name="employeeName" column="ename" />
    <property name="departmentId" column="deptNo" />
    <property name="salary" column="salary" />
  </class>
</hibernate-mapping>

Run the Application :

Main.java
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.otp.hibernate.pojo.Employee;

public class Main {

    public static void main(String[] args) {
        Configuration configuration = new Configuration()
                .configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory factory = configuration.buildSessionFactory(builder
                .build());

        Session session = factory.openSession();

        System.out.println("Reading Partial Entity with One Projection object ");

        Criteria criteria = session.createCriteria(Employee.class);
        Projection projection = Projections.property("salary");
        criteria.setProjection(projection);
        List list = criteria.list();
        Iterator it = list.iterator();

        while (it.hasNext()) {
            Integer sal = (Integer) it.next();
            System.out.println("Employee Salary : " + sal);
        }
        
        System.out.println("Reading Partial Entity with multiple Projection objects ");
        
        Criteria crit2 = session.createCriteria(Employee.class);
        Projection projection1 = Projections.property("salary");
        Projection projection2 = Projections.property("departmentId");
        Projection projection3 = Projections.property("employeeName");
        
        ProjectionList pList = Projections.projectionList();
        pList.add(projection1);
        pList.add(projection2);
        pList.add(projection3);
        crit2.setProjection(pList);
        
        List list2 = crit2.list();

        Iterator it2 = list2.iterator();

        while (it2.hasNext()) {
            Object[] obj = (Object[]) it2.next();
            System.out.println("Salary : " + obj[0]+" DeptId : "+obj[1]+" empName : "+obj[2]);
        }
    }
}

Output :

Console
Reading Partial Entity with One Projection object 
Employee Salary : 6000 Employee Salary : 8000 Employee Salary : 4000 Employee Salary : 5000 Employee Salary : 4000 Employee Salary : 3000 
Reading Partial Entity with multiple Projection objects 
Salary : 6000 DeptId : 101 empName : Chandra Salary : 8000 DeptId : 101 empName : Shekhar Salary : 4000 DeptId : 105 empName : Rahul Salary : 5000 DeptId : 103 empName : Mahesh Salary : 4000 DeptId : 101 empName : Vinay Salary : 3000 DeptId : 105 empName : Vijay

The complete example is available for download.

Happy Learning 🙂

Download Example

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

2 Comments

  1. venkatareddy.avula@gmail.com'
    avulavenkatareddy February 5, 2017 at 12:51 pm - Reply

    Hiii…..
    your website giving the information is awesome but please give the more concepts and depth information and other extra concepts.

    Thank you……………………

  2. ramu27@gmail.com'
    Ram November 7, 2018 at 3:16 am - Reply

    Hi .. thank you for for providing the concept , in this I have one question .. Can we apply pagination on Projection queries ..

Leave A Comment