Hibernate Criteria Example

 

In this example, we will see how to use Hibernate Criteria API to build some criteria queries to retrieve data from database.

 

1. Technologies used

  • Hibernate 4.3.6.Final
  • MySQL 5.1
  • Maven 3.0.5
  • Eclipse 4.5
  • JDK 1.7

 

2. Database table

CREATE TABLE PRODUCT (
   PRODUCT_ID INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT,
   PRODUCT_NAME VARCHAR(30) NOT NULL,
   QUANTITY INT(3) DEFAULT 0,
   UNIT_PRICE FLOAT(10,2) UNSIGNED  DEFAULT 0,
   PRIMARY KEY (PRODUCT_ID)
)

 

3. Project structure

Hibernate Criteria Example

 

4. Model class

File : src/main/java/com/keylesson/persistence/Product.java

package com.keylesson.persistence;

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

@Entity
@Table(name = "PRODUCT")
public class Product {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "PRODUCT_ID", nullable = false)
	private int productId;

	@Column(name = "PRODUCT_NAME", length = 30)
	private String productName;

	@Column(name = "QUANTITY")
	private int quantity;

	@Column(name = "UNIT_PRICE", precision = 10, scale = 2)
	private Float unitPrice;

	public Product() {
	}

	public Product(String productName, int quantity, Float unitPrice) {
		this.productName = productName;
		this.quantity = quantity;
		this.unitPrice = unitPrice;
	}

	public int getProductId() {
		return productId;
	}

	public void setProductId(int productId) {
		this.productId = productId;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public Float getUnitPrice() {
		return unitPrice;
	}

	public void setUnitPrice(Float unitPrice) {
		this.unitPrice = unitPrice;
	}

	@Override
	public String toString() {
		return "Product[" + productName + ", " + quantity + ", " + unitPrice
				+ "]";
	}
}

 

5. Hibernate configuration file

File : src/main/resources/hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbusiness</property>

		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>

		<mapping class="com.keylesson.persistence.Product" />
	</session-factory>
</hibernate-configuration>

 

6. Hibernate Utility

Build the sessionFactory to get a session instance.

package com.keylesson.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	static {
		try {
			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new StandardServiceRegistryBuilder()
					.applySettings(configuration.getProperties()).build();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Throwable ex) {
			System.err.println("Error creating SessionFactory :" + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		sessionFactory.close();
	}

}

 

7. Test It

We will use : restrictions, pagination, sorting and projection.

package com.keylesson.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.keylesson.persistence.Product;
import com.keylesson.util.HibernateUtil;

public class Tester {

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			// Add customer records in database.
			add();

			// Create criteria instance
			Criteria cr = session.createCriteria(Product.class);
			// Using restrictions ..
			// Get products having quantity more than 10 or name starting with Bo
			cr.add(Restrictions.or(Restrictions.gt("quantity", 10), Restrictions.ilike("productName", "Bo%")));
			// Using pagination : get two product records of the result
			cr.setMaxResults(2);
			// Using sorting : sort records in ascending order of quantity
			cr.addOrder(Order.asc("quantity"));
			List<Product> result = cr.list();
			for (Product p : result) {
				System.out.println(p.toString());
			}

			// Using projection
			Criteria crTot = session.createCriteria(Product.class);
			// Get the maximum of salary property.
			crTot.setProjection(Projections.max("unitPrice"));
			List maxPrice = crTot.list();
			System.out.println("Max Price: " + maxPrice.get(0));

		} catch (Exception e) {
			System.err.println("Error creating Customer :" + e);
		}
		HibernateUtil.shutdown();
	}

	/**
	 * Add customer records
	 */
	public static void add() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction t = null;
		try {
			t = session.beginTransaction();
			session.save(new Product("Book", 5, new Float(15.45)));
			session.save(new Product("Pencil", 12, new Float(10.00)));
			session.save(new Product("Satchel", 3, new Float(100.30)));
			session.save(new Product("Book2", 6, new Float(16.00)));
			session.save(new Product("Book3", 10, new Float(36.00)));
			t.commit();
		} catch (Exception e) {
			System.err.println("Error Add :" + e);
			t.rollback();
		} finally {
			session.close();
		}
	}

}

Output :

Hibernate: insert into CUSTOMER (TITLE, NAME) values (?, ?)
Hibernate: insert into ADDRESS (STREET, CITY, COUNTRY, TYPE) values (?, ?, ?, ?)
Hibernate: insert into ADDRESS (STREET, CITY, COUNTRY, TYPE) values (?, ?, ?, ?)
Hibernate: insert into CUSTOMER (TITLE, NAME) values (?, ?)
Hibernate: insert into ADDRESS (STREET, CITY, COUNTRY, TYPE) values (?, ?, ?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)

 

Download source code