Hibernate Projection Example | Projection in Hibernate Example

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see Hibernate Projection with a simple example. As we already discussed in the previous tutorial Hibernate Criteria, If we want to read a partial entity (selected columns) from the database, hibernate has provided us with a Projection interface.
Projection is an interface in Hibernate; it is coming from org.hibernate.criterion package.
Projection can be applied to the Criteria query.
Projection is an Object-Oriented Representation of a query result set.
Hibernate Projection is used to read a partial entity from the database.
If we want to read more than one property from the database, then we have to add Projection objects to ProjectionList, and then we need to set ProjectionList object to Criteria.
The following code is to read the employee name column from the employee table. It will get all the employeNames from the employee table.
Criteria criteria = session.createCriteria(Employee.class); 
Projection projection = Projections.property("employeeName"); 
criteria.setProjection(projection); 
List list = criteria.list();
select ename from employee;
If we want to read more than 1 column (employeeName, salary) with projections, we should have to use ProjectinList class. 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();
On the above example, we will get the salary, departmentId and employeeName from the employee table.
select sal,deptid,ename from emp;
Since those are multiple projections, first we need to add all projections to ProjectionList object and then add ProjectionList object to criteria object.
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 :
<?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 :
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 🙂


Hibernate-Projection-Example

File size: 13 KB
Downloads: 1697


Hibernate Criteria API with Example
Hibernate Restrictions with Example
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Filter Example Xml Configuration
hibernate update query example
Hibernate Right Join Example
What is Association in Java
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Top 10 Advantages of Hibernate
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
Singleton Hibernate SessionFactory Example
Hibernate One To Many Example (XML Mapping)

Hibernate Criteria API with Example
Hibernate Restrictions with Example
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Filter Example Xml Configuration
hibernate update query example
Hibernate Right Join Example
What is Association in Java
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Top 10 Advantages of Hibernate
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
Singleton Hibernate SessionFactory Example
Hibernate One To Many Example (XML Mapping)






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........................









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 ..










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........................




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





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 ..




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


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache