Wednesday, 27 July 2011

Mixed mappings with HBM and mapping by code

Are you ready to embrace and upgrade to NHibernate 3.2 but are unsure about converting all your project hbm.xml files to the new mapping by code syntax?

It is possible to mix and match; that is use your current projects xml files and start to use the mapping by code. So if you find yourself in this position:-
I am ready to start using NHibernate 3.2 in an old project and utilise all the goodness that the mapping by code syntax gives me, but I am not quite ready to move over all my xml files yet.
I realise that one could argue about testing, that is if all my tests cover mappings then the conversion should not cause friction. However some of us are left with named queries right?

The solution is quite simple, first you need to define your web.config (or external hibernate config file) as:-
<configSections>
  <section name="hibernate-configuration"
   type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"     requirePermission="false" />
</configSections>

<hibernate-configuration
   xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="dialect">
      NHibernate.Dialect.MySQL5Dialect
    </property>
    <mapping assembly="Domain.Model" />
  </session-factory>
</hibernate-configuration>
Then in your start up code:-
var mapper = new ModelMapper();
mapper.AddMappings(typeof(CmsMeta).Assembly.GetTypes());
//Notice the .Configure, this is the magic that allows you to
//  use the mixed mappings
var configure = new Configuration().Configure();
configure.DataBaseIntegration(x =>
{
  x.Dialect<MySQL5Dialect>();
  x.ConnectionStringName = "db";
}).CurrentSessionContext<WebSessionContext>();

configure.AddDeserializedMapping(mapping, "Domain");
SessionFactory = configure.BuildSessionFactory();
If you notice we are making a call to .Configure. Because of this call then NHibernate always needs a hibernate-configuration section inside your web.config. We are therefore instructing NHibernate to configure the mappings as usual in web.config and then configure using the new mapping by code syntax (which is based on loquacious).

After you have converted your XML you can remove all references in web.config and change:-
var configure = new Configuration().Configure();
to just:-
var configure = new Configuration();

I personally have used this technique as I still have a few named queries left over in my XML files and have not yet moved them out, therefore this mixed mapping has really helped me out.

You got to love the simplicity of being able to mix old and new, well done to the NHibernate team for taking away some pain points.

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete