Complex mappings very often tend to result in repetitive mapping definitions especially when trying to apply concepts from Domain Driven Design. Value objects (value types as they are called by Hibernate) are a typical example for those kind of repetitive tasks.

Let us assume that you want to keep track of user and time a set of entity types has been updated. So you would add a component mapping to all of the entity mappings where this feature is required.

1
2
3
4
<component name="lastUpdate" class="domain.model.UserAccessReference">
  <property name="at" type="date" column="UPDATE_TIME"></property>
  <property name="by" column="UPDATE_USER_ID"></property>
</component>

This can get really tedious, so you might want to look for a more elegant solution that allows re-using this component mapping. Hibernate does not offer a mapping element that allows to include some externalized mapping fragment. But XML supports including XML documents through it’s DTD entity facility.

So you first start by moving the XML fragment that should be reusable to a file (e.g. domain/model/LastUpdate.xml)

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<component name="lastUpdate" class="domain.model.UserAccessReference">
  <property name="at" type="date" column="LAST_UPD" />
  <property name="by" column="UPD_USR" />
</component>

For mapping file that requires the lastUpdate component an external ENTITY declaration must be added, the entity reference (&lastUpdate;) is a place holder that is replaced by the entity.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" ?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
 [<!--ENTITY lastUpdate SYSTEM "classpath://domain/model/LastUpdate.hbm.xml"-->]>
<hibernate-mapping package="domain.model">
  <class table="TABLE" name="ClassName">
      <!-- some property mappings -->

      <!-- include the standard mapping for the lastUpdate property tuple -->
      &lastUpdate;
  </class>
</hibernate-mapping>

Comments