Sep 23 2008

NHibernate ProxyGenerators added to NHContrib

Tag: NHibernateSymon Rottem @ 7:55 am

It looks like the NHibernate Proxy Generator I discussed in a previous post has been added to the NHibernateForge, the NHibernate community and contribution site.

This is great news for those of you who are stuck in a medium trust environment and are having problems with lazy loading – if you need it then check it out.


Jul 13 2008

NHibernate 2.0 Beta 2 Released

Tag: NHibernate,Open SourceSymon Rottem @ 5:57 pm

For those not watching the mailing list a new beta release of NHibernate 2.0 was released today and word is that if no major issues show up the first release candidate will be made available in another two weeks.

This is a fantastic announcement and although the alphas and betas have been pretty damned good it’s nice to see that things are underway for a production release in the not too distant future – a nice thing to see in any open source project.

Exellent work and kudos to Fabio Maulo and the rest of the team working on the project!


Jun 21 2008

NHibernate 2.0 Alpha 2 Released

Tag: NHibernateSymon Rottem @ 8:56 am

For those not in the know, another alpha release of NHibernate 2.0 was pushed out almost a week ago. Oddly enough I missed that this had come out – it doesn’t appear to have been announced on the NHibernate forums…it did show up on the NHibernate mailing list, however.

The new release addresses a host of bugs and rolls in a couple of improvements. The changelog can be found here.

If you get a chance grab the new release and give it a spin. The developers are looking for feedback and the more the community uses the latest release the more likely we are to see a release candidate in the near future. If you find a bug it can be reported on NHibernate’s Jira at its new location.

A big thanks should go to Fabio Maulo for his excellent work in leading this project.


Mar 31 2008

NHibernate 2.0 Alpha

Tag: NHibernateSymon Rottem @ 10:41 pm

For those of you who aren’t already in the know, the new version of NHibernate has entered it’s alpha release stage. This brings the codebase almost into line with the current Java Hibernate release (3.2) with a couple of exceptions so this is definitely something to write home about.

A few of the key things that I’ve been waiting for in this release are:

  • Inspection/traversal, modification and cloning of ICriteria
  • Table per subclass mapping with a discriminator
  • MultiCriteria
  • Mapping of one class to several tables using the <join> mapping.
  • Events and listeners

The changelog goes some of the way to explain the new changes in more detail than I have, but there’s a more comprehensive rundown on Ayende’s blog if you want a little more meat to chew on. In addition, Fabio Maulo (one of the NHibernate developers) noted that there are a couple of additional features that are notably missing from the changelog; namely the Merge and Persist methods on ISession and extended cascade mappings, unionsubclass and on-delete on the mapping side.

In reality you do need to take some care before upgrading since this is an alpha, but you can rest assured that the code is not brand spanking new, untested and unused. As Ayende mentions in his blog post…

We call this alpha, but many of us are using this in production, so we are really certain in its stability.

Anway, the call is out to start playing with the new version so the developers can get some real-world feedback on how it’s working in your environment and a chance to fix any issues before they give it their blessing for use in more critical and widespread environments. The Castle trunk has been updated to use this new release, so it can’t be too bad now, can it?

If you do decide to upgrade there are some breaking changes to be aware of, but most of them shouldn’t cause you major problems unless you’ve decided to bend and twist NHibernate more that the average user.

Also worthy of note is that there don’t appear to be updated docs available yet, but since most of the features of the new version match those of the production Java version their docs should help you get a good idea of where you are going.

You can keep up with what’s going on with others who are using the new version, get help and can provide feedback on the new NHibernate mailing list as well as the forums. At the moment the mailing list is very active so it’s a great alternative to the forums if you don’t get any response there.

I’ll be taking the new NHibernate for a whirl myself very shortly and will post on my experiences as they happen.


Mar 22 2008

NHibernate Proxy Generator

Tag: NHibernate,Open SourceSymon Rottem @ 4:11 pm

I just stumbled over an interesting post on William C. Pierce‘s blog explaining how to set up NHibernate to run in a a medium trust environment and still get the benefits of lazy loading.

I’ve seen a few queries about how to do use lazy loading under medium trust in the past but have never really investigated it myself having assumed it was just one of those things you couldn’t do since proxies are generated through reflection and reflection permissions are not granted in medium trust environments.

Well it turns out that isn’t the case if you get a little creative.

What William has done is to create his own proxy factory that NHibernate can be configured to use so it will provide proxies that were generated at compile time where you have full trust rather than generating proxies at runtime where the reflection permissions are restricted.
He’s also provided a tool to generate those compile time proxies and released his hours of hard work as the NHibernate Proxy Generator (or NPG) so you don’t have to invest time of your own.  The project is still in it’s infancy but it’s released under the Apache License 2.0 so you can download the source and contribute should you so desire.

William has provided more information on how NHibernate can be configured to run in medium trust and use NPG generated proxies in his blog post so head on over there if you’re stuck with medium trust and still need lazy loading.


Feb 27 2008

More Configuring NHibernate Caches

Tag: NHibernate,ORMSymon Rottem @ 6:52 am

One of my readers recently asked to see a sample of configuring NHibernate caching through the config file after reading my previous post Configuring NHibernate Caches, so here goes. Please bear with me in case there are any typos as this has been rolled by hand.

In this particular example I’m configuring NHibernate to use SysCache for the second level cache and have done it all in the app.config (or web.config if it’s a web application). Note that this is not a fully complete config file but deals with the parts necessary for this example.


<configuration>

<configsections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
<section name="syscache" type="NHibernate.Caches.SysCache.SysCacheSectionHandler,NHibernate.Caches.SysCache"/>
</configsections>

<!--
NHibernate specific configuration.
-->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

<session-factory>

<property name="hibernate.connection.connection_string">Your Connection String</property>
<property name="hibernate.connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="hibernate.dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="hibernate.connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="hibernate.connection.isolation">ReadCommitted</property>
<property name="hibernate.cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property>
<property name="hibernate.cache.use_query_cache">true</property>

<!--
Sets up class and configuration caching for domain classes.
These cache definitions can be tweaked to change how each class is cached.
-->
<class-cache class="Core.User, Core" region="User" usage="read-write"/>
<collection-cache collection="Core.User.Roles" region="User.Roles" usage="read-write"/>

<class-cache class="Core.Role, Core" region="Role" usage="read-write"/>

</session-factory>

</hibernate-configuration>

<!--
Defines Syscache specific configuration
-->
<syscache>

<!-- Class cache regions -->
<cache region="User" expiration="60" priority="3"/>
<cache region="User.Roles" expiration="60" priority="3"/>
<cache region="Role" expiration="60" priority="3"/>

</syscache>

</configuration>

To explain this in a little more detail, the first section deals with telling the application about the configuration sections that will be included in the config file and what handlers to use to interpret them. This is really just standard .NET confg stuff:


<configsections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
<section name="syscache" type="NHibernate.Caches.SysCache.SysCacheSectionHandler,NHibernate.Caches.SysCache"/>
</configsections>

Then we deal with the main NHibernate configuration inside the hibernate-configuration section specified in the configsections:


<property name="hibernate.connection.connection_string">Your Connection String</property>
<property name="hibernate.connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="hibernate.dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="hibernate.connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="hibernate.connection.isolation">ReadCommitted</property>
<property name="hibernate.cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property>
<property name="hibernate.cache.use_query_cache">true</property>

The key things to note here are the hibernate.cache.provider_class and hibernate.cache.use_query_cache properties which are indicating that we should be using the SysCacheProvider for caching and that the query cache should be enabled.

It’s important to note that just adding the hibernate.cache.provider_class property and configuring some of your classes will cause those classes to be put into the second level class cache so that when you attempt to load them using ISession.Get or ISession.Load the the database will only be hit if the matching entity is not found in the cache.

What it will not do, however, is provide any optimisation when you attempt to load entities using an HQL or ICriteria query. Queries will still go to the database to get their results unless, of course, you add the hibernate.cache.use_query_cache property to your configuration and explicitly specify that a query should be cachable using the IQuery.SetCachable(true) method – this must be done explicitly for each query you want to be cached.

When a query is cached the entity IDs in the results of a query will be stored along with the query itself in the second level query cache so that if it’s executed again it will take the list of IDs from the cache and will then re-hydrate the entities from the class cache. Because of this the query cache is useless without the class cache.

The next section deals with configuring the how each class should be cached. This is still part of the hibernate config section:


<!--
Sets up class and configuration caching for domain classes.
These cache definitions can be tweaked to change how each class is cached.
-->
<class-cache class="Core.User, Core" region="User" usage="read-write"/>
<collection-cache collection="Core.User.Roles" region="User.Roles" usage="read-write"/>

<class-cache class="Core.Role, Core" region="Role" usage="read-only"/>

Essentially there are two separate caching definitions to work with; the class-cache element, which deals with how a specific entity type should be cached and the collection-cache element that specifies how an entity’s dependent collection should be cached.

In this example I have elected to cache my User and Role entities as well as the Roles collection on the User entity.

Note that for each mapping you can specify a cache region, which provides additional granularity regarding how specific types should be expired from the cache and a usage that can provide some additional optimization based on whether or not the entities will ever be updated or new entities created by the application.

The final section of my example deals specifically with configuring the SysCache caching provider:

<!--
Defines Syscache specific configuration
-->
<syscache>

<!-- Class cache regions -->
<cache region="User" expiration="60" priority="3"/>
<cache region="User.Roles" expiration="60" priority="3"/>
<cache region="Role" expiration="86400" priority="3"/>

</syscache>

Here you can define the cache regions used in the class-cache and collection-cache mappings above as well as any cache regions you decide to use in queries inside your application. Each cache region describes how long items in that region should stay in the cache before being expired so they will be reloaded again from the database and a priority that indicates which classes should be expired from memory first if the available memory is getting too low.

You can, of course, dump everything into a single cache region, but then all entities will be treated equally in the cache. In my case I want the User entities and their Roles collections to be cached for one minute as this information could be updated externally and I want to have the changes reflected in the application fairly quickly. The Role entities, however, will hardly ever change so I’ve chosen to cache them for a whole day before they should be re-obtained from the database.

Hopefully that clears things up a bit. If there are any questions or comments please feel free to post one – don’t be shy!


Feb 21 2008

Duplicate Madness

Tag: NHibernate,ORMSymon Rottem @ 4:08 pm

One of the things that really kills me in NHibernate is the way that when using joins there are often duplicated entities in the result set. The thing that set me off today is a thread I got involved in on the NHiberate forums where the poster was getting what appeared to be bizarre entity duplication in a list property of an object retreived using ISession.Get.

In this particular case the model was…

Person -< Order -< OrderItem

…where each Person had multiple Orders and each Order had multiple OrderItems. Each of the collections (Person.Orders and Order.OrderItems) had been mapped as bags and for performance reasons (presumably appropriate to their context) the chosen fetch strategy for the collections was set to fetch=”join”.

Everyone with me so far?

The problem here is that if you perform an ISession.Get on a Person who has 1 Order and that Order has 3 OrderItems the Person.Orders collection will contain 3 of the same Order. Why? Well this stems from the way the underlying result set returned by the database works – NHibernate formulates a query with joins in it to get all the data in one go (since that’s what we asked for).

The SQL query for ISession.Get(typeof(Person), 300) would look something like this (select clause omitted for brevity):

...FROM Person p INNER JOIN Orders o ON o.PersonId = p.Id INNER JOIN OrderItems i ON i.OrderId = o.Id WHERE p.Id =300;

(Note that this is hand rolled. And they might not be inner joins, but you get the idea.)

Using our scenario of a Person with 1 Order which has 3 OrderItems from above the result set might look like this:

p.Id p.Name o.Id o.PersonId o.Date i.Id i.OrderId i.Description
300 Symon 595 300 21/02/2008 9876 595 Fishing Rod
300 Symon 595 300 21/02/2008 9877 595 Hat
300 Symon 595 300 21/02/2008 9878 595 Boat

Now, you see the Get operation only returns one Person object but the Orders collection is populated from the result set and there are 3 rows there that contain order information so 3 order items are added to the collection.

Now it’s not quite as bad as it looks. The database operation was efficient because we didn’t have to go to the database multiple times and if you’re thinking we’re using up a chunk of extra memory with the unwanted extra Order items you’d be wrong – the list contains 3 references to the same object in memory, so there’s really only one Order there.

In this particular example the duplicates would not be there if the collections were mapped as Sets rather than Bags. This is because a Set does not allow duplicates so they are filtered out when they’re added.

A more likely situation where you’re going to see this behavior is where you use the default fetch strategy in your mapping but you execute an HQL or ICriteria query with a join:

.SELECT k FROM Cat c WHERE INNER JOIN c.Kittens k WHERE c.Colour = :ParentColour AND k.Colour = :KittenColour

When you call the IQuery.List() method this will return a list of Kitten entities, but since there can be more than one Cat that has the same Kitten in their Kittens collection (Mummy and Daddy, right?) the same Kitten may show up more than once in the result set.

This is, apparently, behavior by design. When the original Hibernate (Java version) developers were making decisions they felt that it made more sense for the returned objects to match the result set – I can’t remember the post I read it from since it was more than a year ago now, so I might not have this exactly right and I’d be happy for someone to correct me.

Again, the solution is to feed the results of the returned IList into a set which will remove the duplicates for you. There is also a feature on the ICriteria API that allows you to provide a result set transformer too – if you don’t believe me you can re-read the documentation…


Feb 12 2008

O/R Mapper Choices

Tag: NHibernateSymon Rottem @ 3:11 pm

I saw this article by Mario Van Damme the other day about some of the decisions you should probably take into account when choosing an Object Relational mapping tool.

Best Practices for Object/Relational Mapping and Persistence APIs

Although published in 2006 it’s a good article on some of the considerations that I didn’t take into account when choosing an ORM and probably should have. Luckily, NHibernate has worked out as a good choice overall

Mind you, when I started with NHibernate I did struggle against transparent persistence – to my mind I should have full control over when all persistence actions take place, so I did everything I could to disable transparent persistence – to my detriment. That said, I’ve learned from my mistakes and have fully embraced NHibernate’s transparent persistence and transactions and all the performance advantages it provides, however there have certainly been some projects where an persistence solution that allows me full control would have been a better choice.

Had I read the Mario’s article I might have had some idea of where I was going before I started.


Feb 10 2008

DDD and NHibernate

Tag: DDD,NHibernate,ORMSymon Rottem @ 12:35 am

I was trawling around the net today and stumbled over a series of posts (some of which are now quite old) by Ben Scheirman about developing applications using DDD with NHibernate. I don’t recall having seen this series when I was starting to get my head around both of these concepts and they would have been invaluable at the time so I thought it would be worth re-posting the links to the posts for posterity’s sake and for those developers out there who are just getting started.

The series was (after having the name refactored a couple of times) called A Journey with Domain Driven Design (and NHibernate). In the series Ben manages manages to cover a few design patterns, some TDD concepts and examples, separation of concerns, configuring NHibernate, writing mapping files and pulling it all together.

Following are the links to the articles and a quick overview of what each part covers:

  • Part 1 – Describes the reasoning behind his approach and the project structure used in the series.
  • Part 2 – Covers the application and its requirements and begins designing the domain model.
  • Part 3 – Demonstrates writing basic unit tests for the domain model.
  • Part 4 – Demonstrates more sophisticated tests that include interactions between domain entities.
  • Part 5 – Database design strategies, configuring NHibernate and starts unit testing the persistence assembly .
  • Part 6 – NHibernate class and component mappings and some tests to check they’re working as expected.
  • Part 7 – NHibernate collection and association mapping.
  • Part 8 – Some refactoring, the introduction to use of the Repository pattern and use of the Template Method design pattern.
  • Part 9 – Wrapping up the feature list and a link to download the latest version of the code.

The series is excellent and recommended reading if you are trying to get off the ground with DDD and NHibernate.


Feb 09 2008

Configuring NHibernate Caches

Tag: NHibernate,ORMSymon Rottem @ 3:05 pm

A little while ago I decided it would be prudent to start using the second level cache in NHibernate to improve performance in a couple of web applications my team and I had written. The database was taking quite a bit of punishment and performance was degrading while the data being queried was often fairly static in nature so caching seemed like the right choice.

I’d seen some samples out there where people had added the cache configuration directives in their .hbm files so off I went and started adding the <cache> element to my class and collection mappings, configured the SysCache provider in my configuration file and voila, we were off and running with the first application. Then I sat down and started thinking…

Now you are probably asking yourself the same question I was – why didn’t I sit down and think first? An excellent question – one I’ll sit down and think about. Hmmm.

The problem was that the applications in question share the same domain model assembly, which in turn share the same NHibernate mapping files but each application has it’s own caching requirements so I couldn’t reuse the new cache settings between applications. For one application we don’t intend to ever write values to a particular class so they could be mapped to the cache as read-only, while in another application the cached value for the same class should be read-write. Since we were looking at using caching for performance reasons it certainly seemed to make sense that we use the cache in the most performant way possible.

After doing a bit of extra reading of the NHibernate docs I realized that you don’t have to add you cache directives to your mapping classes; there’s a single line in the documentation I had missed:

Alternatively (preferrably?), you may specify <class-cache> and <collection-cache> elements in hibernate.cfg.xml.

I guess the lesson here is read the documentation more carefully…

So, after adding the class and collection cache mappings to our NHibernate configuration we also added some cache regions with appropriate expiry periods for each application and turned on the query cache and started up the applications again. The performance difference is quite something – the database load, which was moderately heavy, dropped significantly and the response times for the applications in question suddenly jumped. I never did do any real comparison measurements but the difference was significant enough.

I have noticed, however, that when using the SysCache provider and setting expiration that sometimes the objects aren’t expired from the cache as promptly as I would have expected. I haven’t yet investigated this issue in depth, but it’s nagging at me. I’ll report back when I have more concrete data, but if there’s anyone out there who can shed some light I’d be glad for some feedback.