Skip to main content

How to create and use Example in Hibernate.

If you want to fetch some specific pattern data from database then we use Example.

How to create and use Example in Hibernate.

1. Define your object pattern which type of object you want to fetch

1
2
3
  Userdata user=new Userdata();
  user.setId(6);
  user.setUser("user 6");

2.Create Example using

1
Example example11=Example.create(user);

3. Add example into Criteria

1
2
Criteria criteria2= session.createCriteria(Userdata.class)
		    .add(example11);

How to use Example in hibernate


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
36
37
38
39
40
41
42
43
44
45
 
package com.spy.operation;
import java.util.List;
import javax.persistence.OrderBy;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
public class ProjectionExample
{
	public static void main(String[] args)
	{
		SessionFactory sessionfactory=new Configuration().configure().buildSessionFactory();
		Session session=sessionfactory.openSession();
 
		session.beginTransaction();
 
		Userdata user=new Userdata();
		user.setId(6);
		user.setUser("user 6");
 
 
		//creating Example and passing user object as per requirement
		Example example11=Example.create(user);
 
		//adding example to criteria to get record
		Criteria criteria2= session.createCriteria(Userdata.class)
		.add(example11);
 
 
		List<Userdata> user2=criteria2.list();
		session.getTransaction().commit();
 
		session.close();
 
 
		for (Userdata u1 : user2)
		{
		  System.out.println(u1.getUser());
		}
	}
}

Output:

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