Hibernate Session createCriteria(), contains() and cancelQuery() Example

By Arvind Rai, December 01, 2015
On this page we will provide Hibernate Session createCriteria(), contains() and cancelQuery() example. The method Session.createCriteria() of Hibernate Session returns Criteria instance. We can filter the result using Restrictions class. The method Session.contains() checks if the given instance is available in Hibernate Session or not. The method Session.cancelQuery() cancels the execution of query. We can call this method from another thread safely. Find the example for these Hibernate Session methods.

Sample Data Used in Demo

Hibernate Session createCriteria(), contains() and cancelQuery() Example

Session createCriteria()

Session.createCriteria() accepts entity name and returns the instance of org.hibernate.Criteria to which we can add restriction using Restrictions class of hibernate while fetching data. We use createCriteria() as follows.
List<?> std = session.createCriteria(Student.class).
	add(Restrictions.le("id", 2)).addOrder(Order.asc("name")).list(); 
Find the example.
CreateCriteriaDemo.java
package com.concretepage;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
public class CreateCriteriaDemo {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<?> std = session.createCriteria(Student.class).
				add(Restrictions.le("id", 2)).addOrder(Order.asc("name")).list();
		for(int i = 0; i<std.size(); i++) {
			Student s = (Student)std.get(i);
			System.out.println(s.getId()+", "+ s.getName());
		}
		session.close();
	}
} 
Find the output.
Hibernate: select this_.id as id1_0_0_, this_.name as name2_0_0_ from student this_ where this_.id<=? order by this_.name asc
1, AA
2, BB 

Session contains()

Session.contains() checks if the session contains the given instance. We need to pass instance to this method as an argument. We use it as follows.
session.contains(std));
 
In hibernate every instance has three states transient, detached and persistent. If the instance is in transient or detached states, Session.contains() will return false and in case of persistent state, it returns true. Now find the example for Session.contains().
ContainsDemo.java
package com.concretepage;
import org.hibernate.Session;
public class ContainsDemo {
	Session session = HibernateUtil.getSessionFactory().openSession();
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		//session.contains() returns true for persistent instance.
		Student std = (Student)session.get(Student.class, 1);
		System.out.println(session.contains(std));
		//session.contains() returns false for detached instance.
		session.evict(std);
		System.out.println(session.contains(std));
		//session.contains() returns false for transient object.
		Student s = new Student();
		s.setId(1);
		s.setName("AA");
		System.out.println(session.contains(s));
	}
} 
Find the output.
Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_ from student student0_ where student0_.id=?
true
false
false 

Session cancelQuery()

Session.cancelQuery() is used to cancel the execution of query. We can call this method from another thread safely. We use this method as follows.
session.cancelQuery();
 
Find the example.
CancelQueryDemo.java
package com.concretepage;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.hibernate.Query;
import org.hibernate.Session;
public class CancelQueryDemo {
	Session session = HibernateUtil.getSessionFactory().openSession();
	public static void main(String[] args) {
		ExecutorService exService = Executors.newFixedThreadPool(2);
		CancelQueryDemo ob = new CancelQueryDemo();
		exService.execute(ob.new ThreadOne());
		exService.execute(ob.new ThreadTwo());
	}
	class ThreadOne implements Runnable {
		@Override
		public void run() {
			List<?> std = session.createQuery("FROM Student").list();
			for(int i = 0; i<std.size(); i++) {
				Student s = (Student)std.get(i);
				System.out.println(s.getId()+", "+ s.getName());
			}
		}
	}
	class ThreadTwo implements Runnable {
		@Override
		public void run() {
			session.cancelQuery();
		}
	}
	protected  void finilize() {
		session.close();
	}
} 

Hibernate Utility and Entity class

Find the Hibernate Utility class.
HibernateUtil.java
package com.concretepage;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
    private static SessionFactory sessionFactory ;
    static {
       Configuration configuration = new Configuration().configure();
       StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
	                   .applySettings(configuration.getProperties());
       sessionFactory = configuration.buildSessionFactory(builder.build());
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}  
Find the entity class.
Student.java
package com.concretepage;
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="name")
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us