Java Reference
In-Depth Information
to map values to parameters. Once you have defined your filter, you need to attach the filter
definition to a class. At the end of our User class definition, we specify that it uses a filter
named activatedFilter . We then need to set a condition corresponding to an HQL WHERE
clause for the attached filter. In our case, we used :activatedParam = activated , where
:activatedParam is the named parameter specified on the filter definition, and activated is
the column name from the user table. You should ensure that the named parameter goes on
the left-hand side so that Hibernate's generated SQL doesn't interfere with any joins.
Listing 11-1. Hibernate XML Mapping for User
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hibernatebook.filters.User">
<id name="id" type="int">
<generator class="native"/>
</id>
<property name="username" type="string" length="32"/>
<property name="activated" type="boolean"/>
<filter name="activatedFilter" condition=":activatedParam = activated"/>
</class>
<filter-def name="activatedFilter">
<filter-param name="activatedParam" type="boolean"/>
</filter-def>
</hibernate-mapping>
With the filter definition created and attached to a class with a suitable condition, we
need to activate the filter. The next class, SimpleFilterExample , inserts several user records
into the database, and then immediately displays them to the screen. The class uses a very
simple HQL query ( from User ) to obtain the result set from Hibernate. The displayUsers()
method writes the usernames and activation status out to the console. Before you have
enabled any filters on the database, this method will return the full list of users. Once you
have enabled the first filter ( activatedFilter ) to show only activated users, call the same
displayUsers() method—the results of the query are the same as if you had added a WHERE
clause containing an "activated=true" clause. You can just as easily change the filter's
parameter value to show inactive users, as shown in Listing 11-2.
Search WWH ::




Custom Search