SQL Zone is brought to you in partnership with:

Ashutosh Sharma is working as a Technical Architect with Infosys Technologies Ltd, USA. His area of expertise is Java, J2EE, customized J2EE frameworks and Documentum. He has around 9.5 years of IT experience. He has worked in Services as well as Product companies. He holds a Bachelor's Degree in Computer Science Engineering from Government Engineering College Bhopal(INDIA) and Diploma in Advanced Computing from C-DAC Pune(INDIA). He holds various Sun, Documentum and Brainbench certifications. Ashutosh has posted 1 posts at DZone. View Full User Profile

Introduction to Hibernate Filters

05.14.2009
| 64588 views |
  • submit to reddit

Hibernate is one of the most popular ORM solutions being used in the Java persistence world. In this article we will learn how to use Hibernate filters. A sample application is also provided for the better understanding.

With Hibernate3 there is a new way to filtering the results of searches. Sometimes it is required to only process a subset of the data in the underlying Database tables. Hibernate filters are very useful in those situations. Other approaches for these kind of problems is to use a database view or use a WHERE clause in the query or Hibernate Criteria API.

But Hibernate filters can be enabled or disabled during a Hibernate session. Filters can be parameterized also. This way one can manage the 'visibility' rules within the Integration tier. They can be used in the scenarios where you need to provide the capability of security roles, entitlements or personalization.

When to use Hibernate Filters

Let's take an example, consider a web application that does the reporting for various flights. In future course there is a change 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 small application it is okay to do this, but for a large and complex application it might be a troublesome effort. Moreover it will be like searching each and every SQL query and making the changes in the existing code which have 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 need to be very careful so that they are not changing existing working SQL queries in inadvertent way.

Filters can be used like database views, but parameterized inside the application. This way they are useful when developers have very little control over DB operations. Here I am going to show you the usage of Hibernate filters to solve this problem. When the end users select the status, your 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 selected status. Flight status is maintained at two locations- Hibernate Session and flight status filter.

One of the other use cases of filters I can think of is in the user's view of the organization data. A user can only view the data that he/she is authorized to. For example an admin can see data for all the users in the organization, manager can see the data for all the employees reporting to him/her in his/her group while an employee can only see his/her data. If a user moves from one group to another-with a very minimal change using Hibernate Filters this can be implemented.

Note: This is a very simple application and un-necessary complexity has been taken out to better understand the application of Hibernate filters. Please feel free to add bells and whistles on your own to this sample application.

How to use Hibernate Filters

Hibernate filters are defined in Hibernate mapping documents (hbm.xml file)-which are easy to maintain. One can programmatically turn on or off the filters in the application code. Though filters can't be created at run time, they can be parameterized which makes them quite flexible in nature. We specify the filter on the column which is being used to enable/disable visibility rules. Please go thru the example application in which the filter is applied on flight status column and it must match a named parameter. After that at run time we specify one of the possible values.

Example Application

The example application is a very elementary flight reporting system. Some prior knowledge of Hibernate is required to understand it fully.

Please refer to the code provided with this article. This can be imported as project in Eclipse IDE. You need to download hibernate3.jar under Hibernate Core. MySQL5 is used as the backend DB. MySQL driver viz. mysql-connector-java-5.1.6-bin.jar , Java 1.5 and Eclipse IDE needs to be downloaded from appropriate sources.

A good amount of details in terms of working with Hibernate has been abstracted into HibernateUtil.java so that users with very less experience with Hibernate can also use the sample application. The file 'hibernate.cfg.xml' can be used as it is. This is the hibernate configuration file. This sample application is ready to be executed provided you have MySQL DB already installed. To make it run with other databases, you 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 definitions must contain the name of the filter and the names and types of any filter parameters. Specify filter parameters with the <filter-param> XML element. Filter parameters are similar to the named parameters for HQL queries. We need to specify a':'(colon) before the parameter name/condition. Here is the mapping file from the sample code.

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="data">
<class name="Flight" table="hibernate_filter_demo.flight_db">
<id name="id" type = "int" column="id">
<generator class = "increment"/>
</id>
<property name="flightNo" type="string" length="10" column="flight_No"/>
<property name="source" type="string" length="15" column="source"/>
<property name="destination" type="string" length="15" column="destination"/>
<property name="status" type="string" length="20" column="status"/>
<filter name="statusFilter" condition=":statusParam=status"/>
</class>
<filter-def name="statusFilter">
<filter-param name="statusParam" type="string"/>
</filter-def>

</hibernate-mapping>

 

Note: All the boilerplate hibernate mapping files can be created using the Hibernate tools.

Now attach the filters to class or collection mapping elements. You can attach 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. name and condition. The name references a filter definition (in the sample application it's : statusFilter) while condition is analogous to a WHERE clause in HQL. Please go thru the complete hibernate mapping file from the HibernateFilters.zip archive.

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.

In the java code, we can programmatically enable or disable the filter. By default the Hibernate Session doesn't have any filters enabled on it.

The Session interface contains the following methods:

  • public Filter enableFilter(String filterName)

  • public Filter getEnabledFilter(String filterName)

  • public void disableFilter(String filterName)

The Filter interface contains some of the important methods:

  • public Filter setParameter(String name, Object value)

  • public Filter setParameterList(String name, Collection values)

  • public Filter setParameterList(String name, Object[] values)

setParameter() method is mostly used. Be careful and specify only the type of java object that you 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 you want to use BETWEEN clauses, use two different filter parameters with different names.

Now let's see what we need to do in the java code.

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 condition name should contain one of the possible values for that column. This condition is being set on the filter.

 

 

public class HibernateFilterDemo
{
public static void main(String argsp[])
{
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
insertData("DL6149", "RIC", "JFK", "ontime", session);
....
Filter filter = session.enableFilter("statusFilter");
filter.setParameter("statusParam", "delayed");

showData(session);
....
session.close();
}

public static void insertData(String flightNo, String source,
String destination, String status, Session session)
{
session.beginTransaction();
....
session.getTransaction().commit();
}

public static void showData(Session session)
{
session.beginTransaction();
Query query = session.createQuery("from Flight");
....
session.getTransaction().commit();
}
}

 

 

 

 

Please go thru the source code provided with this article(HibernateFilters.zip). It contains the DDL scripts for creating tables in MySQL, Java Code, Hibernate mapping and configuration file and eclipse project settings. The project can be directly imported into Eclipse IDE. The DDL can let you work with any other Database of your choice too. Please feel free to write to me in case of any issues in terms of executing this sample application.

Conclusion

Hibernate filters is one of the alternatives to DB views, SQL where clause, Hibernate Criteria API.It is a useful way to segregate database concerns from the remaining application code. They help in reducing the complexity of HQL or SQL queries. Filters can be enabled as and when they are required. Enjoy working with Hibernate Filters!

Resources



About the Author

Ashutosh Sharma is working as a Technical Architect with Infosys Technologies, USA. His area of expertise is Java, J2EE, customized J2EE frameworks and Documentum. He has around 9.5 years of IT experience. He has worked in Services as well as Product companies. He holds a Bachelor's Degree in Computer Science Engineering from Government Engineering College Bhopal (INDIA) and Diploma in Advanced Computing from C-DAC Pune(INDIA). He holds various Sun (SCJP 1.2 and SCEA5), Documentum and Brainbench (J2EE Developer) certifications.

 

 

 

Legacy
Article Resources: 
Published at DZone with permission of its author, Ashutosh Sharma.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Yousuf Haider replied on Thu, 2009/05/14 - 3:48pm

Interesting stuff. Another use of Filters that comes to mind is to enable multi-tenancy in applications. For eg. for a particular user you could show only his/her data based on the filter.

 Just a thought. Though I feel there would be some performance implications.

 

-yousuf

Abraham Jacob replied on Thu, 2009/05/14 - 5:51pm

Good article!!!. I always used to wonder what could be the use of Hibernate Filters. It's being written in a very simple language. I liked the sample application. I executed it with Apache Derby and it's working fine.

James Becker replied on Thu, 2009/05/14 - 6:05pm

Excellent write up. Can I use Hibernate filter to have visibilty rules in the Web Tier? I am using Toplink - do you know the similar stuff in Toplink?

Rutherford James replied on Thu, 2009/05/14 - 6:30pm

Good to know about Hibernate Filters. I have been using Hibernate for around 2 years but I haven't used this feature(may be i never come across it). Working example is good one-though it is a simple example, but it's good to understand the concept of Hibernate Filters.

Atul Saxena replied on Thu, 2009/05/14 - 6:42pm

Nice article. Your sample code run as it is. I need not have to do any changes into it. I m using a higher version of MySQL Community Edition and it's working fine with that.

Ron Hunt replied on Thu, 2009/05/14 - 7:19pm

Good one.

Christina Melony replied on Thu, 2009/05/14 - 7:53pm

Very good article. Sample application is good. Good to know about the application of Hibernate Filters. I have never used it in my project....will figure it out where it can be used

De ZB replied on Fri, 2009/05/15 - 12:17am

As interesting or otherwise as the article may or may not be, why is it that there are 7 new comments on this, all saying the same thing, all from new accounts, all registered within a few minutes of each other ?

Rent-a-comment ? 

Manish Sharma replied on Fri, 2009/05/15 - 11:07am

Article is good....is it possible to upload the configuration and DDL for Apache Derby or Pointbase. They are quite easy to set up.

Kelly Robinson replied on Sun, 2009/05/17 - 1:32am

Thanks for the article. I'm more a fan of annotations than XML however. Here's the same Filter definition with Hibernate Annotations:

@Entity
@FilterDef(name="statusFilter", parameters=@ParamDef(name="statusParam", type="string") )
@Filters( {
    @Filter(name="statusFilter", condition=":statusParam=status")
} )
public class Flight { ... } 

Untried, but should work.

David James replied on Mon, 2009/05/18 - 6:48am in response to: Kelly Robinson

Nice article supported by a simple example.

Rubecca Alfred replied on Wed, 2009/05/20 - 8:18am

Good intro and how to for Hibernate filters.

Manish Joshi replied on Fri, 2009/05/22 - 12:55am

Interesting article

Rasheed Latif replied on Sat, 2009/05/30 - 6:43am

Nice Article. Good example

pedro lastorgas replied on Wed, 2009/10/21 - 12:57pm

Excellent article.

I loved it and hated it at the same time.

The more i learn , the more ignorant i know i am.

Cheers.

 

Peter form magos

john green green replied on Sun, 2009/10/25 - 8:47am

Good to know about Hibernate Filters. I have been using Hibernate for around 2 years but I haven't used this feature(may be i never come across it). Working example is good one-though it is nike shoes chinaa simple example, but it's good to understand the concept of Hibernate Filters.

Sanjay Jain replied on Mon, 2014/03/10 - 8:02am

nice article,

can we use hibernate filter for update and delete operation as well, 

as in multi tenancy environment crud operation required based on tenants and 

filter can be useful to read data and represent views but for update and delete 

filter directly not firing queries wirh WHERE clause with tenant id.

Any thoughts ?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.