Way more nifty: Using compression at field level when persisting #2

In a previous post (here) I showed how the contents of a string property could be internally stored as a GZipped byte array for persistence. The code demonstrated how to achieve this, but not in a particularly pretty manner, because I did some nasty hacks inside the property’s setter and getter – i.e. I crammed all the zipping/unzipping stuff directly inside my domain class.

When using NHibernate for persistence you have another option, which I have recently learned about. So let’s rewrite the example from my previous post.

The example looked like this:

As you can see there’s way too much going on in there – we want a persistence ignorant domain model, so we want to go back to the property looking simple, like this:

– and we can actually achieve that, because NHibernate is so freaking cool that I almost cannot believe it. We do it by implementing our own type of database mapping – an IUserType. An implementation of IUserType tells NHibernate the following useful stuff:

  • What is the Sql type of the database column
  • What is the .NET type we want to be able to store/retrieve
  • + some more stuff

– and in addition to this, the implementor must implement the actual object -> db/db -> object mapping.

I implemented the example like this:

– and now my mapping file contains the following mapping:

Note how the type is set to our newly implemented user type.

The advantages over my previous solution include (but are not necessarily limited to):

  1. Your domain model stays PI. Annoying details, like how to actually get away with storing stuff in the database can be put in a place where is does not disturb your eyes and colleagues forever.
  2. You avoid implementing this kind of logic multiple times.
  3. And the corollary to 2: If you need to change the implementation some time, you need only change it in one place.
  4. Debugging is way more fun because the field is the same type as the property.
  5. Is is more efficient because the actual mapping is only performed when storing/retrieving values (which is way less frequent than you’d think because of NHibernate’s built-in caching).

As you can see, this implementation was fairly simple. One disadvantage though, compared to storing the actual string, is that querying is still impossible.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.