Java Reference
In-Depth Information
Using Filters in Your Application
Your application programmatically determines which filters to activate or deactivate for a
given Hibernate session. Each session can have a different set of filters with different parame-
ter values. By default, sessions do not have any active filters—you must explicitly enable filters
programmatically for each session. The
Session
interface contains several methods for work-
ing with filters, as follows:
•
public Filter enableFilter(String filterName)
•
public Filter getEnabledFilter(String filterName)
•
public void disableFilter(String filterName)
These are pretty self-explanatory—the
enableFilter(String filterName)
method activates
the specified filter, the
disableFilter(String filterName)
method deactivates the method, and
if you have already activated a named filter,
getEnabledFilter(String filterName)
retrieves that
filter.
The
org.hibernate.Filter
interface has six methods. You are unlikely to use
validate()
;
Hibernate uses that method when it processes the filters. The other five methods are as follows:
•
public Filter setParameter(String name, Object value)
•
public Filter setParameterList(String name, Collection values)
•
public Filter setParameterList(String name, Object[] values)
•
public String getName()
•
public FilterDefinition getFilterDefinition()
The
setParameter()
method is the most useful. You can substitute any Java object for the
parameter, although its type should match the type you specified for the parameter when you
defined the filter. The two
setParameterList()
methods are useful for using
IN
clauses in your fil-
ters. If you want to use
BETWEEN
clauses, use two different filter parameters with different names.
Finally, the
getFilterDefinition()
method allows you to retrieve a
FilterDefinition
object rep-
resenting the filter metadata (its name, its parameters' names, and the parameter types).
Once you have enabled a particular filter on the session, you do not have to do anything
else to your application to take advantage of filters, as we demonstrate in the following example.
A Basic Filtering Example
Because filters are very straightforward, a basic example allows us to demonstrate most of the
filter functionality, including activating filters and defining filters in mapping documents.
In the following Hibernate XML mapping document (
User.hbm.xml
), we created a filter
definition called
activatedFilter
. The parameters for the filter must be specified with
<filter-param>
XML elements (as shown in Listing 11-1), which use the
<activatedParam>
XML element. You need to specify a type for the filter parameter so that Hibernate knows how
Search WWH ::
Custom Search