Tags

Hibernate mapping files are a frequent source of code duplication. For example, let’s say that all your database tables contain the same set of audit columns. Why should you have to repeat that declaration in every single mapping file? Or maybe you have similarly structured tables with different names, which is also a good opportunity for reuse.

It is possible to reuse the same Hibernate XML mapping snippet from other mapping files by utilizing XML entities.

XML snippet in ca/gc/agr/common/jms/domain/portal/PortalEventMessage.xml:

<!-- This fragment is included from an another hbm -->

	<version name="lockSeqNum" type="int" column="LOCK_SEQ_NUM" />
	
	<property name="partyId" type="string" column="PARTY_ID" length="20" not-null="true" />
	<property name="fromAppNameEnglish" type="string" column="SOURCE_SYSTEM_NAME_ENG" length="100" not-null="true"  />        
	<property name="fromAppNameFrench" type="string" column="SOURCE_SYSTEM_NAME_FR" length="100" not-null="true" />
	
        ... etc ...
	
	<property name="createdDtm" type="timestamp" column="CREATED_DTM" />
	<property name="createdUserOid" type="long" column="CREATED_USER_OID" />
	<property name="updatedDtm" type="timestamp" column="UPDATED_DTM" />
	<property name="updatedUserOid" type="long" column="UPDATED_USER_OID" />

Hibernate mapping::

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" [
    <!ENTITY commonMapping SYSTEM "classpath://ca/gc/agr/common/jms/domain/portal/PortalEventMessage.xml">
    ]>

<hibernate-mapping>

    <class name="ca.gc.agr.common.jms.domain.portal.PortalEventMessage" table="PIN_PORTAL_EVENT" dynamic-update="true">

        <id name="oid" type="long" column="PORTAL_EVENT_OID" unsaved-value="0">
            <generator class="sequence">
                <param name="sequence">pin_portal_event_seq</param>
            </generator>
        </id>

		&commonMapping;

    </class>
    
</hibernate-mapping>

Make sure that the XML snippet is on the classpath and you are done.