Hibernate is most popular technology in Java development. Most of the real world application they used kind of hibernate technology with fine tuned mechanisms. If you are in java development I hope the following code snippet will be helpful you to make your application faster.
What I’m going to explain in this post is how to load the chunk of data with efficient manner.Hibernate Criteria helps to do this as we wish. Think about if you have millions of data in your data table and you are going to display the data in your application.
package com.jubiliation.example.pagination;setFirstResult(int firstResult) API method of Criteria to set the first result per page.
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class PaginationInHibernateWithCriteriaAPI {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
for (int i = 0; i < 100; i++) {
Employee employee = new Employee();
employee.setName("employe_"+i);
employee.setCreated(new Date());
session.save(employee);
}
session.getTransaction().commit();
}
catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session = sessionFactory.getCurrentSession();
int pageNumber = 2;
int pageSize = 10;
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(Employee.class);
criteria.setFirstResult((pageNumber - 1) * pageSize);
criteria.setMaxResults(pageSize);
List<Employee> employees = (List<Employee>) criteria.list();
if (employees!=null) {
System.out.println("Total Results:" + employees.size());
for (Employee employee : employees) {
System.out.println(employee.getId() + " - " + employee.getName());
}
}
session.getTransaction().commit();
}
catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
}
maxResults(int maxResults) API method of Criteria to set the max results of each page.
Comments
Post a Comment