CodesJava

Easy learning with example program codes

Hibernate criteria pagination query example


Criteria interface provides the methods for performing pagination operations.

Methods of Criteria interface used for pagination query:

1. setFirstResult(int firstResult): Set the first row of your result based on the firstResult value. Row index starts from 0.

Syntax: public Criteria setFirstResult(int firstResult)

2. setMaxResults(int maxResults): Set the maximum number of records in your result.

Syntax: public Criteria setMaxResults(int maxResults)

Example:

Student.java

/**
 * This class represents a persistent class for Student.
 * @author codesjava
 */
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.codesjava.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 codesjava
 */
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 java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import com.codesjava.persistence.HibernateUtil;
 
/**
 * This class is used for the hibernate operations.
 * @author codesjava
 */
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("Bharat");
        student1.setLastName("Jaiswal");
        student1.setClassName("MCA final");
        student1.setRollNo("MCA/07/15");
        student1.setAge(27);
 
        student2.setFirstName("Richi");
        student2.setLastName("Gora");
        student2.setClassName("MCA final");
        student2.setRollNo("MCA/07/35");
        student2.setAge(27);
 
        student3.setFirstName("Rajesh");
        student3.setLastName("Garg");
        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);
        criteria.setFirstResult(1);
        criteria.setMaxResults(2);
        List<Student> stuList = (List<Student>) criteria.list();
        for(Student stu : stuList){
            System.out.println("First Name: " + stu.getFirstName());
            System.out.println("Last Name: " + stu.getLastName()); 
            System.out.println("Class: " + stu.getClassName()); 
            System.out.println("RollNo: " + stu.getRollNo()); 
            System.out.println("Age: " + stu.getAge());     
        } 
 
        //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 * from ( select row_.*, rownum 
rownum_ from ( select this_.Student_Id as Student1_0_0_, 
this_.First_Name as First2_0_0_, this_.Last_Name as 
Last3_0_0_, this_.Class as Class0_0_, this_.RollNo as 
RollNo0_0_, this_.Age as Age0_0_ from Student this_ )
 row_ ) where rownum_ <= ? and rownum_ > ?
First Name: Pardeep
Last Name: Janra
Class: MCA final
RollNo: MCA/07/35
Age: 27
First Name: Sandy
Last Name: Sethi
Class: MCA final
RollNo: MCA/07/19
Age: 27

Download this example.
 
Next Topic: Hibernate criteria projections query example.
Previous Topic: Hibernate criteria ordering query example.

Related Topics:

Hibernate criteria basic query example.
Hibernate criteria restrictions query example.
Hibernate criteria ordering query example.
Hibernate criteria pagination query example.
Hibernate criteria projections query example.

 

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki