Example of @Where in Hibernate
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.
State.java
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; @Entity @Table(name = "state") @Where(clause="id>1") public class State implements Serializable{ private static final long serialVersionUID = 1L; @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; } }
HibernateUtil.java
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() .addPackage("com.concretepage.persistence") .addProperties(prop) .addAnnotatedClass(State.class) .buildSessionFactory(); } 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()); } session.close(); } }
Table: state
1 UP 2 MP 3 HP
Output
2 MP 3 HP