Filter is one of the major component in hibernate. These filters are used to select some specific data from the database. There are different types of filters available. In this article we will discuss about hibernate filters.
Why we use Hibernate Filters
With Hibernate3 there is a new way to filtering the review of searches. Sometimes it is necessary to only process a subset of the record in the underlying Database having tables. Hibernate filters are essential in those situations. Other methodologies for these kind of problems is to use a database view or use a WHERE clause in the query or Hibernate Criteria API.
When to use Hibernate Filters
Suppose a web application that does the reporting for various flights. In future course there is some changes in requirement such that flights are to be shown as per their status (on time, delayed or cancelled).
This can also be done using a WHERE clause within the SQL SELECT query or Hibernate’s HQL SELECT query. For a mini application it is fine to do this, but for a huge and complex application it might be a tiresome effort. Although it will be like searching each and every SQL query and making the changes in the existing code. But it has been thoroughly tested.
This can also be done using Hibernate's Criteria API but that also means changing the code at numerous places that is all working fine. Moreover in both the approaches, one needs to be very cautious so that they are not changing existing working SQL queries in inadvertent way.
Filters can be used like database views and data dictionary, but parameterized inside any application. This way they are essential when developers have very little control over DB operations. Here weare going to show you the usage of Hibernate filters to solve this problem. When the end users select the status, our application activates the flight's status for the end user's Hibernate session.
Any SQL query will only return the subset of flights with the user chooses status. Flight status is maintained at two places- Hibernate Session and flight status filter.
How to use Hibernate Filters
Hibernate filters are defined in Hibernate mapping documents (hbm.xml file)-which are easy to manage. One can programmatically turn active or sleep mode the filters in the application code. Though filters cannot be created dynamically, they can be parameterized which makes them quite portable in nature. We suggest the filter on the column which is being used to enable/disable visibility rules. Please go through the demo application in which the filter is applied on flight status column and it must match a named parameter. After that we provide dynamic values at run time.
The example application is a very elementary flight reporting system. Some previous knowledge of Hibernate is necessary to understand it fully.
A good amount of details in terms of working with Hibernate has been abstracted into HibernateUtil.java so that novice users can also use the sample application. The file 'hibernate.cfg.xml' can be used as it is. There is one hibernate configuration file. This application is ready to be executed provided you have MySQL DB previously installed. To make it run with other databases, we need to make the changes in 'hibernate.cfg.xml' file. DDL is also provided as part of the Zip file.
Getting started with the example
First define filters in the Hibernate mapping documents, using the <filter-def> XML element. These filter declaration should contain the name of the filter and the names and types of any filter parameters. Demonstrate filter parameters with the <filter-param> XML element. Filter parameters are same to the named parameters for HQL queries. We need to specify a':'( colon) before the parameter condition. Here is the mapping file from the code.
Listing 1: Mapping File
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD "
<class name="Flight" table="hibernate_filter_demo.flightdb">
<id name="id" type = "int" column="id">
<generator class = "increment"/>
<property name="fliteNo" type="string" length="10" column="flight_No"/>
<property name="src" type="string" length="15" column="source"/>
<property name="dest" type="string" length="15"column="destination"/>
<property name="info" type="string" length="20" column="info"/>
<strong><filter name="statusFilter" condition=":statusParam=status"/>
<filter-param name="statusParam" type="string"/>
Now attach the filters to class or collection mapping elements. We can join a single filter to more than one class or collection. To do this, you add a <filter> XML element to each class or collection. The <filter> XML element has two attributes viz. values and condition. The value references a filter definition while condition is analogous to a WHERE clause in HQL. Let’s see the complete coding from the HibernateFilters.zip archive.
Note: Each <filter> XML element must correspond to a <filter-def> element. It may be possible to have more than one filter for each filter definition, and each class may have more than one filter.
Concept is to define all the filter parameters in one place and then refer them in the individual filter conditions.
In the java code, we can programmatically enable or hide the filter. By default the Hibernate Session doesn't have any filters visible on it.
Methods of Session Interface:
- public Filter enableFilter(String NameofFilter)
- public Filter getEnabledFilter(String NameofFilter)
- public void disableFilter(String NameofFilter)
Methods of Filter Interface:
- public Filter setParameter(String NameofFilter, Object value)
- public Filter setParameterList(String NameofFilter, Collection values)
- public Filter setParameterList(String NameofFilter, Object values)
setParameter() method is almost used. Be careful and define only the type of java object that we have mentioned in the parameter at the time of defining filter in the mapping file.
The two setParameterList() methods are useful for using IN clauses in your filters. If we want to use BETWEEN clauses, must use two different filter parameters with different names.
At the time of enabling the filter on session-use the name that you have provided in the mapping file for the filter name for the corresponding column in the table. Similarly string name should contain one of the possible values for that particular column.
Listing 2: This condition is set on the filter
public class HibernateFilterDemo
public static void main(String argsp)
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
insertData("DL6159", "RFC", "JCK", "dealy 15 min", session);
<strong>Filter filter = session.enableFilter("statusFilter");
public static void insertData(String fliteNo, String src,
String dest, String info, Session ses)
24.public static void showData(Session session)
Query query = session.createQuery("from Flight");
Please go through the source code provided with this article (HibernateFilters.zip). It posses the DDL scripts for creating tables in MySQL, Hibernate mapping,Java Code, and configuration file and eclipse project settings. The project can be directly installed into Eclipse IDE. The DDL can let us work with any other Database of our choice too.
Hibernate filters is one of the best optionto DB views, Hibernate Criteria API and SQL where clause.It is an efficient way to separate database concerns from the remaining application code. They help in minimizing the complexity of HQL or SQL queries. Filters can be made visible/on as and when they are required.