Home  >  Hibernate 4

Hibernate 4 Criteria Query Tutorials with Examples using JPA 2

By Arvind Rai, February 10, 2015
In this page we will learn Hibernate 4 Criteria Query tutorials with examples using JPA 2. Hibernate suggest to use javax.persistence.criteria.CriteriaQuery instead of org.hibernate.Criteria. Here in this page we will provide different complete examples for CriteriaQuery. We will discuss typed and tuple both criteria query in our examples. To instantiate CriteriaQuery, we need javax.persistence.criteria.CriteriaBuilder. We will cover below points.
1. Fetch an Entity
2. Fetch One Column
3. Fetch Multiple Columns
4. Fetch Column Using Expression
5. Fetch Columns using Wrapper Class
6. Use Tuple to Fetch Columns

Use JPA 2 javax.persistence.criteria.CriteriaQuery Class instead of Hibernate org.hibernate.Criteria

To use CriteriaQuery we have to follow below steps.
1. Create persistence.xml to configure database configuration.
2. Fetch javax.persistence.criteria.CriteriaBuilder and javax.persistence.EntityManager by using javax.persistence.Persistence.createEntityManagerFactory().
3. Instantiate CriteriaQuery as CriteriaBuilder.createQuery() for typed criteria quires and CriteriaBuilder.createTupleQuery() for Tuple criteria query.
4. Use CriteriaQuery .select() and CriteriaQuery.multiselect() to select columns
5. Use CriteriaQuery.from() to assign entity name to fetch data.
6. Use CriteriaQuery.where() to apply condition for filtering the result.
7. Finally use EntityManager.createQuery() to create query and on its instance apply getResultList() or getSingleResult ()and get result.

Software Required to Run Examples

Find the software to run examples.
1. Java 6
2. Eclipse
3. Gradle
4. MySQL

Prepare Database

We are using MySQL for our demo. Find the schema.
Table: student
CREATE TABLE `student` (
	`id` INT(11) NULL DEFAULT NULL,
	`name` VARCHAR(50) NULL DEFAULT NULL,
	`age` INT(10) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB; 
The inserted rows are given below.
Hibernate 4 Criteria Query Tutorials with Examples using JPA 2

build.gradle

Find the gradle file to resolve the required JAR.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'hibernate-4'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
	compile 'org.hibernate:hibernate-core:4.3.8.Final'
	compile 'org.hibernate:hibernate-entitymanager:4.3.6.Final'
	compile 'mysql:mysql-connector-java:5.1.34'
}  

persistence.xml

Find the persistence.xml in which we will do database configuration.
persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="com.concretepage">
        <description>CriteriaQuery Demo</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.concretepage.pojo.Student</class> 
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/concretepage"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value=""/>
        </properties>
    </persistence-unit>
</persistence> 

Hibernate Utility class to get CriteriaBuilder and EntityManager

Find the utility class that will provide CriteriaBuilder and EntityManager.
HibernateUtil.java
package com.concretepage.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
public class HibernateUtil {
 	private static final EntityManagerFactory emFactory;
	static {
		   emFactory = Persistence.createEntityManagerFactory("com.concretepage");
	}
	public static CriteriaBuilder getCriteriaBuilder(){
		CriteriaBuilder builder = emFactory.getCriteriaBuilder();
		return  builder;
	}
	public static EntityManager getEntityManager(){
		return emFactory.createEntityManager();
	}
} 

Entity Class used in Example

Find the student entity class which we are using for the demo.
Student.java
package com.concretepage.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
	@Id
	@Column(name="id")
	private int id;
	@Column(name="age")
	private int age;
	@Column(name="name")
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 

Fetch an Entity

Find the example to fetch an entity with all columns. While instantiating CriteriaQuery , we need to pass entity class name.
FetchEntity.java
package com.concretepage;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.concretepage.pojo.Student;
import com.concretepage.util.HibernateUtil;
public class FetchEntity {
	public static void main(String[] args) {
		CriteriaBuilder builder = HibernateUtil.getCriteriaBuilder();
		EntityManager em = HibernateUtil.getEntityManager();
		CriteriaQuery<Student> criteriaQuery = builder.createQuery(Student.class);
		Root<Student> studentRoot = criteriaQuery.from(Student.class);
		criteriaQuery.select(studentRoot);
		criteriaQuery.where(builder.equal(studentRoot.get("name"),"Ram"));
		List<Student> students = em.createQuery(criteriaQuery).getResultList();
		for ( Student student : students) {
		    System.out.println("id:"+student.getId()+", age:"+student.getAge());
		}
	}
} 
Find the output.
id:1, age:20
id:3, age:22 

Fetch One Column

To fetch one column, instantiate CriteriaQuery with the data type of that column.
FetchOneColumn.java
package com.concretepage;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.concretepage.pojo.Student;
import com.concretepage.util.HibernateUtil;
public class FetchOneColumn {
	public static void main(String[] args) {
		CriteriaBuilder builder = HibernateUtil.getCriteriaBuilder();
		EntityManager em = HibernateUtil.getEntityManager();
		CriteriaQuery<String> criteriaQuery = builder.createQuery(String.class);
		Root<Student> studentRoot = criteriaQuery.from(Student.class);
		criteriaQuery.select(studentRoot.get("name").as(String.class));
		criteriaQuery.where(builder.equal(studentRoot.get("age"),"22"));
		List<String> nameList = em.createQuery(criteriaQuery).getResultList();
		for (String name : nameList) {
		    System.out.println(name);
		}
	}
} 
Find the output.
Mahesh
Ram 

Fetch Multiple Columns

As we need more than one column, the object of CriteriaQuery will be created by passing Object[] array.
FetchMultipleColumns.java
package com.concretepage;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.concretepage.pojo.Student;
import com.concretepage.util.HibernateUtil;
public class FetchMultipleColumns {
	public static void main(String[] args) {
		CriteriaBuilder builder = HibernateUtil.getCriteriaBuilder();
		EntityManager em = HibernateUtil.getEntityManager();
		CriteriaQuery<Object[]> criteriaQuery = builder.createQuery(Object[].class);
		Root<Student> studentRoot = criteriaQuery.from(Student.class);
		criteriaQuery.select(builder.array(studentRoot.get("id"),studentRoot.get("age")));
		criteriaQuery.where(builder.equal(studentRoot.get("name"),"Ram"));
		List<Object[]> dataArray = em.createQuery(criteriaQuery).getResultList();
		for (Object[] values : dataArray) {
		    Integer id = (Integer) values[0];
		    Integer age = (Integer) values[1];
		    System.out.println("id:"+id+", age:"+age);
		}
	}
} 
Find the output.
id:1, age:20
id:3, age:22 

Fetch Column Using Expression

To use expression while fetching column values, assign CriteriaQuery with the required data type and use CriteriaBuilder instance to get function like avg, max and min etc.
FetchColumnWithExpression.java
package com.concretepage;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.concretepage.pojo.Student;
import com.concretepage.util.HibernateUtil;
public class FetchColumnWithExpression {
	public static void main(String[] args) {
		CriteriaBuilder builder = HibernateUtil.getCriteriaBuilder();
		EntityManager em = HibernateUtil.getEntityManager();
		CriteriaQuery<Integer> criteriaQuery = builder.createQuery(Integer.class);
		Root<Student> studentRoot = criteriaQuery.from(Student.class);
		criteriaQuery.select(builder.max(studentRoot.get("age").as(Integer.class)));
		criteriaQuery.where(builder.equal(studentRoot.get("name"),"Ram"));
		Integer maxAge = em.createQuery(criteriaQuery).getSingleResult();
		System.out.println("Max Age:"+ maxAge);
	}
} 
Find the output.
Max Age:22 

Fetch Columns using Wrapper Class

We can use a wrapper class to fetch columns using CriteriaQuery. Instantiate CriteriaQuery by passing wrapper class name.
FetchWrapper.java
package com.concretepage;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.concretepage.pojo.Student;
import com.concretepage.util.HibernateUtil;
public class FetchWrapper {
	public static void main(String[] args) {
		CriteriaBuilder builder = HibernateUtil.getCriteriaBuilder();
		EntityManager em = HibernateUtil.getEntityManager();
		CriteriaQuery<StudentWrapper> criteriaQuery = builder.createQuery(StudentWrapper.class);
		Root<Student> studentRoot = criteriaQuery.from(Student.class);
		criteriaQuery.select(builder.construct(StudentWrapper.class, studentRoot.get("id"),studentRoot.get("age")));
		criteriaQuery.where(builder.equal(studentRoot.get("name"),"Ram"));
		List<StudentWrapper> wrapperList = em.createQuery(criteriaQuery).getResultList();
		for (StudentWrapper w : wrapperList) {
		    int id = w.getId();
		    int age = w.getAge();
		    System.out.println("id:"+id+", age:"+age);
		}
    }
} 
Find the wrapper for student entity.
StudentWrapper.java
package com.concretepage;
public class StudentWrapper {
	private int id;
	private int age;
	public StudentWrapper(int id,int age){
		this.id = id;
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
} 
Find the output.
id:1, age:20
id:3, age:22 

Use Tuple to Fetch Columns

We can use Tuple class to fetch columns. Instantiate CriteriaQuery using CriteriaBuilder.createTupleQuery().
FetchDataUsingTuple.java
package com.concretepage;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.concretepage.pojo.Student;
import com.concretepage.util.HibernateUtil;
public class FetchDataUsingTuple {
	public static void main(String[] args) {
		CriteriaBuilder builder = HibernateUtil.getCriteriaBuilder();
		EntityManager em = HibernateUtil.getEntityManager();
		CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
		Root<Student> studentRoot = criteriaQuery.from(Student.class);
		criteriaQuery.multiselect(studentRoot.get("id"),studentRoot.get("age"));
		criteriaQuery.where(builder.equal(studentRoot.get("name"),"Ram"));
		List<Tuple> tupleList = em.createQuery(criteriaQuery).getResultList();
		for (Tuple tuple : tupleList) {
		    Integer id = (Integer)tuple.get(0);
		    Integer age = (Integer)tuple.get(1);
		    System.out.println("id:"+id+", age:"+age);
		}
	}
} 
Find the output.
id:1, age:20
id:3, age:22 
Now we are done. Happy Learning.

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus

Sitewide-Feb4of4234x60






Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us