Criteria API in Hibernate

In some case(i.e. Query for generating Report) your query contains so many condition and if you want change some condition then it becomes difficult and hard to maintain it.

For that hibernate provide Criteria API, in which you can add restriction as per your requirement and it is Very easy to maintain.

Let’s see Criteria Example.

We have already created Userdata table.
user_data

Let’s create some criteria for that table.

CriteriaApi.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
package com.spy.operation;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
public class CriteriaApi
{
public static void main(String[] args)
{
	SessionFactory sf=new Configuration().configure().buildSessionFactory();
	Session session=sf.openSession();
	session.beginTransaction();
 
	Criteria criteria1= session.createCriteria(Userdata.class);
 
	//criteria for equal
	criteria.add(Restrictions.eq("user", "user 6"));
 
	// criteria for greater than or equal
	// criteria.add(Restrictions.ge("id",6));
 
	List<Userdata> user=criteria.list();
	session.getTransaction().commit();
 
	session.close();
	for (Userdata userdata : user)
	{
     	System.out.println(userdata.getUser());
	}
	}
}

Output:

1
2
3
4
 
Hibernate: select this_.id as id1_0_, this_.user as user1_0_ from Userdata
this_ where this_.user=?
user 6

Leave a Reply

Your email address will not be published. Required fields are marked *