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 ?
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With