Projections Hibernate

Projections class provides the methods to perform the operation on a particular column.

Commonly used methods of Projections class:

1. Projections.rowCount: Return the total no. of rows.

Syntax:

Projections.rowCount()

2. Projections.avg: Return the average of a specified property.
Syntax:

Projections.avg("property")

3. Projections.countDistinct: Return the distinct count of a property.
Syntax:

Projections.countDistinct("property")

4. Projections.max: Return the maximum value of a property.
Syntax:

Projections.max("property")

5. Projections.min: Return the minimum value of a property.

Syntax:

Projections.min("property")

6. Projections.sum: Return the sum of a property.

Syntax:

Projections.sum("property")

Example: Projections Hibernate

Student.java

/**
 * This class represents a persistent class for Student.
 * @author w3schools
 */
public class Student {
	//data members
	private int studentId;
	private String firstName;
	private String lastName;
	private String className;
	private String rollNo;
	private int age;
 
	//no-argument constructor
	public Student(){
 
	}
 
	//getter and setter methods
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getRollNo() {
		return rollNo;
	}
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
 
}

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <property name="dialect">
           org.hibernate.dialect.OracleDialect
        </property>
        <property name="connection.url">
           jdbc:oracle:thin:@localhost:1521:XE
        </property>
        <property name="connection.username">
           system
        </property>
        <property name="connection.password">
           oracle
        </property>
        <property name="connection.driver_class">
           oracle.jdbc.driver.OracleDriver
        </property>
        <property name="hbm2ddl.auto">
           update
        </property>
        <property name="show_sql">
           true
        </property>
 
        <mapping resource="student.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration>

student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
 
 <class name="com.w3schools.business.Student" table="Student">
  <id name="studentId" type="int" column="Student_Id">
	<generator class="native"></generator>
  </id>
 
  <property name="firstName" column="First_Name" type="string"/>
  <property name="lastName" column="Last_Name" type="string"/>
  <property name="className" column="Class" type="string"/>
  <property name="rollNo" column="RollNo" type="string"/>
  <property name="age" column="Age" type="int"/>
 
 </class>
 
</hibernate-mapping>

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * This is a utility class for getting the hibernate session object.
 * @author w3schools
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory = 
                                           buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
    	SessionFactory sessionFactory = null;
        try {
        	//Create the configuration object.
        	Configuration configuration = new Configuration(); 
        	//Initialize the configuration object 
                //with the configuration file data
        	configuration.configure("hibernate.cfg.xml");
        	// Get the SessionFactory object from configuration.
        	sessionFactory = configuration.buildSessionFactory();
        }
        catch (Exception e) {
           e.printStackTrace();
        }
        return sessionFactory;
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
}

HibernateTest.java

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
 
import com.w3schools.persistence.HibernateUtil;
 
/**
 * This class is used for the hibernate operations.
 * @author w3schools
 */
public class HibernateTest {
   public static void main(String args[]){
        //Create the student object.
        Student student1 = new Student();
        Student student2 = new Student();
        Student student3 = new Student();
 
        //Setting the object properties.
        student1.setFirstName("Roxy");
        student1.setLastName("Malik");
        student1.setClassName("MCA final");
        student1.setRollNo("MCA/07/32");
        student1.setAge(28);
 
        student2.setFirstName("Neeraj");
        student2.setLastName("Chechi");
        student2.setClassName("MCA final");
        student2.setRollNo("MCA/07/33");
        student2.setAge(29);
 
        student3.setFirstName("Sahdev");
        student3.setLastName("Gorila");
        student3.setClassName("MCA final");
        student3.setRollNo("MCA/07/19");
        student3.setAge(27);
 
        //Get the session object.
        Session session = 
                HibernateUtil.getSessionFactory().openSession();
 
        //Start hibernate transaction.
        session.beginTransaction();
 
        //Persist the student object.
        session.save(student1);
        session.save(student2);
        session.save(student3);
 
        //Commit hibernate transaction.
        session.getTransaction().commit();
 
        //select a student record using Criteria pagination query	
        Criteria criteria = session.createCriteria(Student.class);
 
        // give total row count.
        criteria.setProjection(Projections.rowCount());
        Integer count = (Integer) criteria.uniqueResult();
        System.out.println("No. of records: " + count); 
 
        // give maximum age.
        criteria.setProjection(Projections.max("age"));
        Integer maxAge = (Integer) criteria.uniqueResult();
        System.out.println("Max age: " + maxAge); 
 
        //Close hibernate session.
        session.close();
 
    }
}

Output:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: select count(*) as y0_ from Student this_
No. of records: 3
Hibernate: select max(this_.Age) as y0_ from Student this_
Max age: 29

Download this example.