NHibernate Forge
The official new home for the NHibernate for .NET community

NHibernate Filters

One of the more interesting ability of NHibernate is to selectively filter records based on some global filters. This allow us to very easily create global where clauses that we can flip on and off at the touch of a switch.

Let us take a look at see what I mean.

We define the filter effectiveDate:

<filter-def name="effectiveDate">
	<filter-param name="asOfDate" type="System.DateTime"/>
</filter-def>

A filter definition is most commonly just a set of parameters that we can define, which will later be applied to in the appropriate places. An example of an appropriate place would be Post.PostedAt, we don’t want to show any post that was posted at a later time than the effective date. We can define this decision in the mapping, like this:

<class name="Post"
		   table="Posts">
		<id name="Id">
			<generator class="identity"/>
		</id>
		
		<property name="Title"/>
		<property name="Text"/>
		<property name="PostedAt"/>
		
		
		<filter name="effectiveDate"
						condition=":asOfDate >= PostedAt"/>
	</class>

And now we can start play:

s.CreateCriteria<Post>()
	.SetMaxResults(5)
	.List();

s.EnableFilter("effectiveDate")
	.SetParameter("asOfDate", DateTime.Now);

s.CreateCriteria<Post>()
	.SetMaxResults(5)
	.List();

Who do you think this will generate?

Well, the first query is pretty easy to understand:

image

But the second one is much more interesting:

image

We have selectively applied the filter so only posted posted after the 16th can be seen.

This is a very powerful capability to have, since we can use this globally, to define additional condition. For that matter, we can apply it in multiple places, so comments would also be so limited, etc.

For that matter, we can also put filters on associations as well:

<set name="Comments"
	 table="Comments">
	<key column="PostId"/>
	<one-to-many class="Comment"/>
	<filter name="effectiveDate"
					condition=":asOfDate >= PostedAt"/>
</set>

And trying to access the Comments collection on a Post would generate the following SQL when the filter is active:

image

Nice, isn’t it?


Posted may 04 2009, 10:33 a.m. by Ayende
Filed under: , , ,

Comments

Fred Morrison wrote re: NHibernate Filters
on 05-04-2009 13:10

Please repost this article.  The condition definition in the XML of the first example is unreadable because it is right-justified and cut off.  The second one is also difficult to read because of a similar right-justification issue.

Ayende wrote re: NHibernate Filters
on 05-04-2009 19:51

Fred,

They are not right justified, they are indented.

You can also try reading it here:

ayende.com/.../nhibernate-filters.aspx

Fred Morrison wrote re: NHibernate Filters
on 05-06-2009 15:57

Thanks.  The alternate location is much more readable.

Powered by Community Server (Commercial Edition), by Telligent Systems