Today, we are going to discuss about Hibernate Criteria Query, HCQ is more object oriented as compared to Hibernate Query Language. It can be used as an alternative to Hibernate Query Language in some scenarios. It can be used by applications which have many search criteria’s. You may apply filtration rules and logical conditions easily with help of Hibernate Criteria Query.
Let’s discuss simple example to start with Hibernate Criteria Query.
We will make a class Course and we will perform operation on this class using the Hibernate Criteria Query.
Listing 1: Course class.
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
*
* @author Anurag
*/
@Entity
public class Course implements Serializable {
@Id
@GeneratedValue
@Column(name = "C_ID")
private Long id;
private String name;
private int duration;
public Course() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Course(String n, int dur) {
name = n;
duration = dur;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In the code above we defined a class Course with fields like id, name, duration and defined the setter and getter function for these.
We set the id to be auto generated and also we set the name for this column to be C_ID.
Now we will define the configuration file:
Listing 2: hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateArt</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">csanurag</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="model.Course"/>
</session-factory>
</hibernate-configuration>
We defined the configuration parameter for the database and we also defined the mapping class which in this case is class Course.
Now we will define the Utility class which will be used to obtain instance of session factory:
Listing 3: Utility class.
package Main;
/**
*
* @author Anurag
*/
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class Utility {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
In the code above we made a sessionFactory object and initialized this within a static block so that sessionFactory get initialized whenever an object of this class is made. We made a getter to obtain the sessionFactory object.
Now we make the main class which will use the hibernate criteria query:
Listing 4: App2 class.
package Main;
/**
*
* @author Anurag
*/
import java.util.Iterator;
import java.util.List;
import model.Course;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class App2 {
public static void main(String args[]) {
SessionFactory sf = Utility.getSessionFactory();
Session s = sf.getCurrentSession();
Transaction tx = s.beginTransaction();
//Creating a Criteria for the Course Class.
Criteria crit = s.createCriteria(Course.class);
List course = crit.list();
//Iterating through each record found in Course class.
for (Iterator it = course.iterator(); it.hasNext();) {
Course c = (Course) it.next();
//Printing the result on the console
System.out.println("ID: " + c.getId());
System.out.println("Name: " + c.getName());
System.out.println("Duration: " + c.getDuration());
}
tx.commit();
}
}
Firstly, We made a session instance with help of session factory object and started the transaction. We create a Criteria instance for the class Contact and obtained all records for Contact using the crit.list() which makes a sql query and run in database to obtain the records.
We save this course object using the session variable and commit the transaction to make the changes permanent.
After run it shows all the records which were there in the Course class.
This is all for today’s article. We will discuss some more operation on Hibernate Criteria Query in the coming articles. Hope you enjoyed the article. See you next time.







See the prices for this post in Mr.Bool Credits System below: