Hibernate Criteria load all objects from table

Learn how to get the instance of Criteria and then load all the objects from table in Hibernate program.

Hibernate Criteria load all objects from table

Hibernate Criteria load all objects from table - Learn how to load all the data from a table (not good choice if large amount of data is present in table).

This is the first example of Hibernate Criteria which loads all the data from 'employee' table in our application. In some cases you have to load all the data from a table then you can easily use the Hibernate Criteria load all objects from table. You should use this query with care as in production environment if data is huge it will crash the JVM.

Let's discuss about the API of loading all the records.

Here is the video tutorial of "Hibernate Criteria load all objects from table":

The org.hibernate.Criteria is very simplified API in Hibernate for selective fetching of entities by using the Criterion objects. Following is the example of creating an instance of Criteria and fetching all the entities:

Criteria criteria= session.createCriteria(Employee.class);
List employees = criteria.list();

In this above code we creating the instance of Criteria by calling createCriteria() method on session object and passing the Employee.class as parameter.

The criteria.list() method returns the list of all the Employee objects.

Here is the complete code of Hibernate Criteria which loads all 'Employee' objects from table:

package net.roseindia;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import net.roseindia.model.*;

/**
 * @author Deepak Kumar Web: http://www.roseindia.net
 */

public class HibernateCriteriaLoadAllExample {
	public static void main(String[] args) throws Exception {

		SessionFactory sessFact = HibernateUtil.getSessionFactory();
		Session session = sessFact.getCurrentSession();
		org.hibernate.Transaction tr = session.beginTransaction();

		Criteria criteria = session.createCriteria(Employee.class);
		List employees = criteria.list();

		Iterator itr = employees.iterator();
		while (itr.hasNext()) {

			Employee emp = (Employee) itr.next();
			System.out.println(emp.getId());
			System.out.println(emp.getEmpName());
			System.out.println(emp.getEmpMobileNos());
		}

		tr.commit();
		System.out.println("Data displayed");
		sessFact.close();
	}
}

Here is the screen shot of the Eclipse Project:

Hibernate Criteria load all objects from table

Here is the code of the model class used in the example:

package net.roseindia.model;
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import javax.persistence.Table;
/**
 * @author Deepak Kumar
 * Web: http://www.roseindia.net
 */
@Entity
@Table(name = "employee")
public class Employee implements Serializable{

	@Id
	@GeneratedValue
	@Column(name="id")
	private int id;	

	@Column(name="emp_name")
	private String empName;

	@Column(name="emp_address")
	private String empAddress;	  

	@Column(name="emp_mobile_nos")
	private String empMobileNos;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpAddress() {
		return empAddress;
	}

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}

	public String getEmpMobileNos() {
		return empMobileNos;
	}

	public void setEmpMobileNos(String empMobileNos) {
		this.empMobileNos = empMobileNos;
	}

}

The code of hibernate.cfg.xml file used in the project:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="net.roseindia.model.Employee" />

</session-factory>
</hibernate-configuration>

Here is the code of utility class which contains a method to get the SessionFactory:

package net.roseindia;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */
public class HibernateUtil {
	private static final SessionFactory sessionFactory;

	private static ServiceRegistry serviceRegistry;

	static {

		try {

			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		} catch (Throwable th) {

			System.err.println("Enitial SessionFactory creation failed" + th);

			throw new ExceptionInInitializerError(th);

		}

	}

	public static SessionFactory getSessionFactory() {

		return sessionFactory;

	}
}

In this section you have learned how to use the Hibernate Criteria Query to fetch all data from a table. Read more Hibernate Criteria Query examples.

Download the Source code of the project discussed here.

Check more Hibernate 4.2 tutorials.