Hibernate filters
Hibernate3 provides an innovative new approach to handling data with “visibility” rules. A Hibernate filter is a global, named, parameterized filter that can be enabled or disabled for a particular Hibernate session.
Hibernate3 has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level.
A filter criteria allows you to define a restriction clause similar to the existing “where” attribute available on the class and various collection elements.
These filter conditions, however, can be parameterized. The application can then decide at runtime whether certain filters should be enabled and what their parameter values should be.
Filters can be used like database views, but they are parameterized inside the application.
Defining a filter
<filter name="statusFilter" condition="std_status like :status" /> <filter-def name="statusFilter"> <filter-param name="status" type="string" /> </filter-def>
Enabling filter and passing parameter in Dao
Filter filter = session.enableFilter("statusFilter"); filter.setParameter("status", "status");
Student.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.candidjava.hibernate.Student" table="student"> <id name="id" type="long" column="std_No"> <generator class="increment" /> </id> <property name="name" column="std_Name" not-null="true" /> <property name="degree" column="std_Degree" /> <property name="phone" column="std_Phone" /> <property name="status" column="std_status" /> <filter name="statusFilter" condition="std_status like :status" /> </class> <filter-def name="statusFilter"> <filter-param name="status" type="string" /> </filter-def> </hibernate-mapping>
Get or fetch record using hibernate filter
public List<Student> getStudentfilter(String status){ List<Student> list = null; try { Session session = getSession();// getting sessionImpl reference Filter filter = session.enableFilter("statusFilter"); filter.setParameter("status", "status"); list = session.createCriteria(Student.class).list(); } catch (HibernateException e) { System.out.println(e.getMessage()); } return list; }
Download