Home Hibernate Examples Criteria Hibernate Criteria Between

Ask Questions?

View Latest Questions


 
 

Hibernate Criteria Between
Posted on: April 6, 2011 at 12:00 AM
Advertisement
In this tutorial you will learn about the hibernate criteria between method

Hibernate Criteria Between

The Criteria Between method provides some numeric range to search result. Suppose you want to search student record whose roll no between 1 to 5. Then for this you will write code as

Criteria criteria = session.createCriteria(Student.class);
	criteria.add(Restrictions.like("name", "John"));
	criteria.add(Restrictions.between("rollNo", 1, 5));
	List list=criteria.list();

An example of Hibernate Criteria Between is given below

CriteriaBetween.java

package net.roseindia.main;

import java.util.Iterator;
import java.util.List;

import net.roseindia.bean.Student;
import net.roseindia.util.HibernateUtil;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class CriteriaBetween {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().openSession();

		Object object;

		try {
			// Creating Criteria Object
			Criteria criteria = session.createCriteria(Student.class);
			criteria.add(Restrictions.like("name", "John"));
			criteria.add(Restrictions.between("rollNo", 0, 5));
			List list=criteria.list();
			Iterator result=list.iterator();
			while(result.hasNext()){
				object=result.next();
				System.out.println(((Student) object).getRollNo()+"\t"+ ((Student) object).getName()+"\t"+ ((Student) object).getCourse()+"\t"+ ((Student) object).getAddress());
			}
			
		} catch (HibernateException e) {

			e.printStackTrace();
		} finally {
			session.close();
		}

	}
}

When you run this application it will display message as shown below:

Hibernate: select this_.roll_no as roll1_0_0_, this_.name as name0_0_, this_.course as course0_0_, this_.address as address0_0_ from student this_ where this_.name like ? and this_.roll_no between ? and ?
1 John MCA Delhi

Download Complete Source Code

Related Tags for Hibernate Criteria Between:


DMCA.com