Java Reference
In-Depth Information
CHAPTER 11
n n n
Filtering the Results
of Searches
Y our application will often need to process only a subset of the data in the database tables.
In these cases, you can create a Hibernate filter to eliminate the unwanted data. Filters pro-
vide a way for your application to limit the results of a query to data that passes the filter's
criteria. Filters are not a new concept—you can achieve much the same effect using SQL
database views—but Hibernate offers a centralized management system for them.
Unlike database views, Hibernate filters can be enabled or disabled during a Hibernate
session. In addition, Hibernate filters can be parameterized, which is particularly useful when
you are building applications on top of Hibernate that use security roles or personalization.
When to Use Filters
As an example, consider a web application that manages user profiles. Currently, your appli-
cation presents a list of all users through a single web interface, but you receive a change
request from your end user to manage active users and expired users separately. For this
example, assume that the status is stored as a column on the user table.
One way to solve this problem is to rewrite every HQL SELECT query in your application,
adding a WHERE clause that restricts the result by the user's status. Depending on how you built
your application, this could be an easy undertaking or it could be complex, but you still end
up modifying code that you have already tested thoroughly, potentially changing it in many
different places.
With Hibernate 3, you can create a filter restriction for the user status. When your end
user selects the user type (active or expired), your application activates the user status filter
(with the proper status) for the end user's Hibernate session. Now, any SELECT queries will
return the correct subset of results, and the relevant code for the user status is limited to two
locations: the Hibernate session and the user status filter.
The advantage of using Hibernate filters is that you can programmatically turn filters on
or off in your application code, and your filters are defined in your Hibernate mapping docu-
ments for easy maintainability. The major disadvantage of filters is that you cannot create new
filters at run time. Instead, any filters your application requires need to be specified in the
proper Hibernate mapping document. Although this may sound somewhat limiting, the fact
that filters can be parameterized makes them pretty flexible. For our user status filter example,
only one filter would need to be defined in the mapping document (albeit in two parts). That
225
Search WWH ::




Custom Search