Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate : map to fields or properties?

When you create your mapping files, do you map your properties to fields or properties :

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Foo" namespace="Foo.Bar" >
  <class name="Foo" table="FOOS" batch-size="100">
    [...]
    <property name="FooProperty1" access="field.camelcase" column="FOO_1" type="string" length="50" />
    <property name="FooProperty2" column="FOO_2" type="string" length="50" />
    [...]
  </class>
</hibernate-mapping>

Of course, please explain why :)

Usually, I map to properties, but mapping to fields can enable to put some "logic" in the getters/setters of the properties.

Is it "bad" to map to fields ? Is there a best practice ?

like image 680
mathieu Avatar asked Sep 24 '08 20:09

mathieu


3 Answers

I map to properties. If I find it necessary, I map the SETTER to a field. (usually via something like "access=field.camelcase").

This lets me have nice looking Queries, e.g. "from People Where FirstName = 'John'" instead of something like "from People Where firstName/_firstName" and also avoid setter logic when hydrating my entities.

like image 168
Gilligan Avatar answered Nov 18 '22 01:11

Gilligan


Properties are also useful in the case you need to do something funky with the data as it comes in and out of persistant storage. This should generally be avoided, but some rare business cases or legacy support sometimes calls for this.

(Just remember that if you somehow transform the data when it comes back out with the getter, NHibernate will (by default) use the return from the getter and save it that way back to the database when the Session is flushed/closed. Make sure that is what you want.)

like image 35
Jon Adams Avatar answered Nov 18 '22 02:11

Jon Adams


I map to properties, I haven't come across the situation where I would map to a field... and when I have I augment my B.O. design for the need. I think it allows for better architecture.

like image 1
Sara Chipps Avatar answered Nov 18 '22 00:11

Sara Chipps