Filtering data is one of the most common Task of an application. This is usually achieved by adding WHERE clauses to your queries. In case the filters are defined dynamically by the user it becomes a more complex issue. A very powerful option for creating dynamic conditions to your applications are Criteria API, however it's likely that when conditions change, you will need to apply changes in your Criteria queries as well.
A valid alternative are Data Filter, which allow placing conditions in your Entity configuration files thus achieving a true dynamic filtering mechanism. Although Data Filters cannot be created at runtime, you can parametrize it, thus making it very flexible. Let's see an example:
<hibernate-mapping package="data"> <class name="Worker" table="Worker_table"> <id name="id" type = "int" column="id"> <generator class = "increment"/> </id> <property name="name" type="string" length="10" column="worker_name"/> <property name="address" type="string" length="15" column="worker_address"/> <property name="wage" type="int" column="worker_wage"/> <filter name="wageFilter" condition=":wageParam=wage"/> </class> <filter-def name="wageFilter"> <filter-param name="wageParam" type="int"/> </filter-def> </hibernate-mapping>
Note: Each <filter> XML element must correspond to a <filter-def> element. It is possible to have more than one filter for each filter definition, and each class can have more than one filter. Idea is to define all the filter parameters in one place and then refer them in the individual filter conditions.
So far, all you've done is define and apply the filter. The results of a query are filtered only after the filter is enabled and parameterized in the application for a particular session. You enable the filter by calling the enableFilter() method on the session, which takes the globally unique filter name as an input parameter. This method returns a Filter instance. The returned Filter instance accepts runtime arguments; you set the parameters you've defined.
The implementation method is as follows:
Session session = getSession(); Filter filter = session.enableFilter("wageFilter"); filter.setParameter("wageParam", 1000); List<Worker> wo = session.createQuery("from Worker")).list();