<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div style="color: #20124d;">
<p>In this tutorial of Criteria in Hibernate Example we will discuss about the Criteria API of hibernate it is using for fetching data from the database in the Hibernate.</p>
<p>There are three way to pulling data from the database in the Hibernate.</p>
</div>
<ol style="text-align: left;">
<li style="color: #20124d;"><b>Using session methods</b>(get() and load() methods) -limited control to accessing data</li>
<li style="color: #20124d;"><b>Using HQL</b> &#8211; Slightly more control using where clause and other clauses but there are some problems here&#8230; is more complicated to maintain in case of bigger queries with lots of clauses.</li>
<li><b style="color: #20124d;">Using Criteria API</b></li>
</ol>
</div>
<h2 style="color: blue;"><i><b>WHAT IS CRITERIA API?</b></i></h2>
<div style="color: #20124d;">
<p>The API (Application Programming Interface) of Hibernate Criteria provides an elegant way of building dynamic query on the persistence database.</p>
</div>
<div style="color: #20124d;">
<p>The hibernate criteria API is very Simplified API for fetching data from Criterion objects. The criteria API is an alternative of HQL (Hibernate Query Language) queries. It is more powerful and flexible for writing tricky criteria functions and dynamic queries</p>
<h2><b>1. Using Criteria API to create criteria:</b></h2>
</div>
</div>
<pre class="highlight">Criteria criteria = session.createCriteria(Student.class); 
</pre>
<h2> 2. <b>The Criteria API supports all the comparision operators</b></h2>
<div></div>
<div style="color: #20124d;">such as =, <;, >;, >;=,=<;, etc in the supported Expression class eq(), lt(), gt(), le() , ge() respectively.</div>
<pre class="highlight">Criteria criteria = session.createCriteria(Student.class); 
 
criteria.add(Restrictions.eq("studentName", "Dinesh Rajput")); 
 
criteria.add(Restrictions.le("rollNumber", 1)); 
 
</pre>
</div>
<h2 style="color: blue;"><b>3. Criteria ordering query</b></h2>
<div style="color: #20124d;">The result is sort by &#8220;studentName&#8221; in ascending order.</div>
<pre class="highlight">Criteria criteria = session.createCriteria(Student.class); 
criteria.addOrder(Order.asc("studentName")); 
</pre>
<p>The result is sort by &#8220;studentName&#8221; in descending order.</p>
<pre class="highlight">Criteria criteria = session.createCriteria(Student.class); 
criteria.addOrder(Order.desc("studentName")); 
</pre>
<h2 style="color: blue;"><b>4. Criteria paging the result</b></h2>
<div></div>
<div style="color: #20124d;">Criteria provide some functions to make pagination extremely easy. Starting from the 5th record, and retrieve the next 10 records from database.</div>
<pre class="highlight">Criteria criteria = session.createCriteria(Student.class); 
criteria.setMaxResults(10); 
criteria.setFirstResult(5); 
</pre>
<div id="ads-id" align="center"></div>
<h2><b>Problem with Criteria API</b></h2>
<div style="color: #20124d;"><b>1. Performance issue</b></div>
<div style="color: #20124d;">You have no way to control the SQL query generated by Hibernate, if the generated query is slow, you are very hard to tune the query, and your database administrator may not like it.</div>
<div style="color: #20124d;"></div>
<div style="color: #20124d;"><b>2. Maintenance issue</b></div>
<div style="color: #20124d;">All the SQL queries are scattered through the Java code, when a query went wrong, you may spend time to find the problem query in your application. On the others hand, named queries stored in the Hibernate mapping files are much more easier to maintain.</div>
</div>
<p><b>Student.java</b></p>
<pre class="highlight">package com.sdnext.hibernate.tutorial.dto; 
 
import java.io.Serializable; 
 
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="STUDENT") 
public class Student implements Serializable 
{ 
 
 /** 
 * serialVersionUID 
 */ 
 private static final long serialVersionUID = 8633415090390966715L; 
 @Id 
 @Column(name="ID") 
 @GeneratedValue(strategy=GenerationType.AUTO) 
 private int id; 
 @Column(name="STUDENT_NAME") 
 private String studentName; 
 @Column(name="ROLL_NUMBER") 
 private int rollNumber; 
 @Column(name="COURSE") 
 private String course; 
 public int getId() { 
 return id; 
 } 
 public void setId(int id) { 
 this.id = id; 
 } 
 public String getStudentName() { 
 return studentName; 
 } 
 public void setStudentName(String studentName) { 
 this.studentName = studentName; 
 } 
 public int getRollNumber() { 
 return rollNumber; 
 } 
 public void setRollNumber(int rollNumber) { 
 this.rollNumber = rollNumber; 
 } 
 public String getCourse() { 
 return course; 
 } 
 public void setCourse(String course) { 
 this.course = course; 
 } 
 public String toString() 
 { 
 return "ROLL Number: "+rollNumber+"| Name: "+studentName+"| Course: "+course; 
 } 
} 
</pre>
<p><b>hibernate.cfg.xml</b></p>
<pre class="highlight"><;hibernate-configuration>; 
 <;session-factory>; 
 <;!-- Database connection settings -->; 
 <;property name="connection.driver_class">;com.mysql.jdbc.Driver<;/property>; 
 <;property name="connection.url">;jdbc:mysql://localhost:3306/hibernateDB2<;/property>; 
 <;property name="connection.username">;root<;/property>; 
 <;property name="connection.password">;root<;/property>; 
 
 <;!-- JDBC connection pool (use the built-in) -->; 
 <;property name="connection.pool_size">;1<;/property>; 
 
 <;!-- SQL dialect -->; 
 <;property name="dialect">;org.hibernate.dialect.MySQLDialect<;/property>; 
 
 <;!-- Enable Hibernate's automatic session context management -->; 
 <;property name="current_session_context_class">;thread<;/property>; 
 
 <;!-- Disable the second-level cache -->; 
 <;property name="cache.provider_class">;org.hibernate.cache.NoCacheProvider<;/property>; 
 
 <;!-- Echo all executed SQL to stdout -->; 
 <;property name="show_sql">;true<;/property>; 
 
 <;!-- Drop and re-create the database schema on startup -->; 
 <;property name="hbm2ddl.auto">;update<;/property>; 
 
 
 <;mapping class="com.sdnext.hibernate.tutorial.dto.Student">; 
 
 <;/mapping>;<;/session-factory>; 
 <;/hibernate-configuration>; 
</pre>
<p><b>HibernateTestDemo.java</b></p>
<pre class="highlight">package com.sdnext.hibernate.tutorial; 
 
import java.util.List; 
 
import org.hibernate.Criteria; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.cfg.AnnotationConfiguration; 
import org.hibernate.criterion.Restrictions; 
 
import com.sdnext.hibernate.tutorial.dto.Student; 
 
 
public class HibernateTestDemo { 
 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) 
 { 
 SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); 
 Session session = sessionFactory.openSession(); 
 session.beginTransaction(); 
 
 Criteria criteria = session.createCriteria(Student.class); 
 criteria.add(Restrictions.eq("studentName", "Dinesh Rajput")); 
 
 List students = criteria.list(); 
 
 for(Student student : students) 
 { 
 System.out.println(student); 
 } 
 session.getTransaction().commit(); 
 session.close(); 
 } 
 
} 
</pre>
<div style="background-color: #ff99cc; border-width: thin; border: solid;">
<div style="color: blue;"><b>Output:</b></div>
<div style="color: red;">log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).</div>
<div style="color: red;">log4j:WARN Please initialize the log4j system properly.</div>
<p>Hibernate: select this_.ID as ID0_0_, this_.COURSE as COURSE0_0_, this_.ROLL_NUMBER as ROLL3_0_0_, this_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT this_ where this_.STUDENT_NAME=?<br />
<b>ROLL Number: 1| Name: Dinesh Rajput| Course: MCA</b></p>
</div>
<div class="separator" style="clear: both; text-align: center;"></div>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2016/12/criteria.jpg" width="640" height="124" border="0" /></div>
<p> ;</p>
</div>
<p><b> In the <a href="https://dineshonjava.com/p/understanding-restrictions.html">Next Chapter</a> we will discuss more about the <a href="https://dineshonjava.com/p/understanding-restrictions.html">Criteria Query with Restriction</a>.</b><br />
<b><br />
</b> <b><br />
<;<;<a style="font-family: Times, 'Times New Roman', serif;" href="https://dineshonjava.com/p/named-queries.html">Previous Chapter 29</a><;<; <a href="https://dineshonjava.com/p/understanding-restrictions.html">>;>;Next Chapter 31</a>>;>;</b></p>
<p> ;</p>
</div>