Tuesday, October 19, 2010

CF9 hibernate file includes.

This was so cool I had to repost it. After you've defined a few hibernate.hbmxml files it gets annoying to have type the same properties on every class. My fingers were getting sore to complain a little. After a reference shown to me by Tony Nelson, Mark Mandal had a great post on "includes in the hibernate file". Check it out.

If you notice in the hibernate.hbmxml below there is a line that says "&common;".

hibernate.hbmxml

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
[ <!ENTITY common SYSTEM "common.hbm.xml"> ]
>
<hibernate-mapping>

<class entity-name="User" lazy="true" name="cfc:beforeandafter.app.model.User" table="`User`">
&common;
<property name="firstName" type="string">
<column name="First_Name" length="200" />
</property>
<property name="lastName" type="string">
<column name="Last_Name" length="200" />
</property>
<property name="emailAddress" type="string">
<column name="Email_Address" length="200" />
</property>
<property name="password" type="string">
<column name="Password" length="200" />
</property>
<bag name="projects">
<key column="User_ID" />
<one-to-many class="cfc:beforeandafter.app.model.Project" />
</bag>
<bag name="projectRatings">
<key column="User_ID" />
<one-to-many class="cfc:beforeandafter.app.model.ProjectRating" />
</bag>
</class>
</hibernate-mapping>


&common; points to file called common.hbm.xml. Within common.hbm.xml file I defined all my similiar properties and just include it on all my classes.

common.hbm.xml

<id name="id" type="int">
<column length="10" name="ID" />
<generator class="identity" />
</id>
<property name="isDeleted" type="boolean">
<column name="isDeleted" />
</property>
<property name="createdBy" type="int">
<column length="10" name="Created_By" />
</property>
<property name="createdOn" type="timestamp">
<column name="Created_On" />
</property>
<property name="updatedBy" type="int">
<column length="10" name="Modified_By" />
</property>
<property name="updatedOn" type="timestamp">
<column name="Modified_On" />
</property>

Make sure your include file ends in .xml and not .hbmxml otherwise it won't work. Made my life a ton a easier. Thanks Mark and Tony for sharing this.