Fluent NHibernate (previously covered by InfoQ) is an alternative to using XML mappings in NHibernate. Fluent NHibernate is using a fluent interface allowing one to define mappings in code instead of XML. Some people in the community have complained about the lack of documentation for Fluent NHibernate and as a response James Gregory recently announced the official Wiki for Fluent NHibernate.
Examples of documentation found in the Wiki are:
- An introduction
- How to create your first Fluent NHibernate project
- How to convert an existing NHibernate application to Fluent NHibernate.
The Wiki shows a typical mapping scenario with both XML and Fluent NHibernate. Using XML it would look something like this:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="QuickStart" assembly="QuickStart"> <class name="Cat" table="Cat"> <id name="Id"> <generator class="identity" /> </id> <property name="Name"> <column name="Name" length="16" not-null="true" /> </property> <property name="Sex" /> <many-to-one name="Mate" /> <bag name="Kittens"> <key column="mother_id"/> <one-to-many class="Cat"/> </bag> </class> </hibernate-mapping>
The same mapping using Fluent NHibernate would look like this:
public class CatMap : ClassMap
{
public CatMap()
{
Id(x => x.Id);
Map(x => x.Name)
.WithLengthOf(16)
.Not.Nullable();
Map(x => x.Sex);
References(x => x.Mate);
HasMany(x => x.Kittens);
}
}
They continue by saying:
While the separation of code and XML is nice, it can lead to several undesirable situations.
They then list some examples:
- Due to XML not being evaluated by the compiler, you can rename properties in your classes that aren't updated in your mappings; in this situation, you wouldn't find out about the breakage until the mappings are parsed at runtime.
- XML is verbose; NHibernate has gradually reduced the mandatory XML elements, but you still can't escape the verbosity of XML.
- Repetitive mappings - NHibernate HBM mappings can become quite verbose if you find yourself specifying the same rules over again. For example if you need to ensure all
string
properties must benot-null
, and have a length of1000
, and allint
s must have a default value of-1
.
In August last year, Oren Eini (a.k.a. Ayende Rahien), pointed out that Fluent NHibernate didn’t add any value because there had to be a mapping class per entity. Since then however, the project has evolved and they now have the concept of Auto Mapping, which is what Ayende was asking for. The Auto Mapping feature uses a set of conventions to automatically map all entities, not requesting a mapping class per entity.