Home  >  Hibernate

Example of @Where in Hibernate

By Arvind Rai, May 27, 2013
@Where in hibernate can be applied at entity level. With the help of @Where, we can use where class to fetch the data. The entity will be populated only for those data for which @Where clause returns true. Find the example below. Find the example.

package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Where;
@Table(name = "state")
public class State  implements Serializable{
	private static final long serialVersionUID = 1L;
	@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;

package com.concretepage.util;
import java.util.List;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.State;
public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
		static {
		 try {
				Properties prop= new Properties();
				prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
				prop.setProperty("hibernate.connection.username", "root");
				prop.setProperty("hibernate.connection.password", "");
				prop.setProperty("hibernate.hbm2ddl.auto", "update");
				prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
				concreteSessionFactory = new AnnotationConfiguration()
		  } catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		public static Session getSession()
				throws HibernateException {
			return concreteSessionFactory.openSession();
		public static void main(String... args){
			Session session=getSession();
	        List<State> states = session.createCriteria(State.class).list();
	        for(State s: states){
	        	System.out.println(s.getId()+" "+s.getName());

Table: state
 1  UP
 2  MP
 3  HP

 2 MP
 3 HP
As we can see that in the table there are three rows but we got only two rows. This is because of @Where clause applied on the entity as @Where(clause="id>1")

©2022 concretepage.com | Privacy Policy | Contact Us