Monday , February 27 2017
Home / Hibernate / Hibernate Projection with Example

Hibernate Projection with Example

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 more than one property, 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 employee name : Here we are getting only one property employee name. This is some thing like “select ename from emp” in SQL. If we want to add 2 or more projections we can go with ProjectionList like below:

Multiple Hibernate Projection Example :

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


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 :

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 chandrashekhar

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+ ,

Check Also

Hibernate Criteria API with Example

In this tutorial, we are going to learn about Hibernate Criteria API. While working with …

One comment

  1. venkatareddy.avula@gmail.com'

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

    Thank you……………………

Leave a Reply

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