In a complex application a persistent entity is typically used by multiple use cases. These use cases put different requirements on mapping such a persistent entity. For example, in a simple case only basic attributes must be mapped whereas in a more complex situation for the same entity a larger set of attributes (+ relationships) must be mapped. When mapping a persistent entity, tradeoffs must be made regarding performance and the required code to implement the solution. For the above scenario a developer would probably just map all of the persistent attributes (regardless whether they are required in all of the use casesor not) and eventually map relationships with some lazy loading enabled. Dealing with it this way mostly works even in larger projects but can totally fail in others (especially when mappings are created by more than one developer and no design rules are in place).

Hibernate provides a mechanism to deal with this kind of troubles very well. One can actually provide multiple mappings for a single persistent class through the mapping attribute ‘entity-name’. For example I had a situation where an entity had a primary key but also an alternate key which was used heavily in other entities for referencing this one.

So I just created 2 different mappings for this one class, mapping different attributes as id.

1
2
3
4
5
6
7
8
9
  <class name="PersistentClass" table="TABLE" entity-name="PC1">
      <id name="id" column="ID" />
      <property name="attribute column="ALTERNATE_ID"/>
  </class>

  <class name="PersistentClass" table="TABLE" entity-name="PC2">
      <property name="id" column="ID" />
      <id name="attribute column="ALTERNATE_ID"/>
  </class>

When referring to a specific mapping the ‘entity-name’ attribute is used

1
  <many-to-one name="reference" entity-name="PC2" column="ALTERNATE_REF"/>

When using the Hibernate API, look out for overloaded methods that allow passing in a entity-name!

Comments