Using Hibernate for enumerations / type codes
I am trying to setup the Hibernate XML files such that enumerations are accessed as string values rather than class instances.
The DB schema:
table MyEntity (EntityId, EnumerationId)
table MyEnumeration (EnumerationId, EnumerationValue)
This provides a mapping of many MyEntity rows to one MyEnumeration row. An example of MyEnumeration could be countries.
Hibernate hbm2hbmxml produces:
<hibernate-mapping>
<class name="MyEntity" table="MyEntity">
<many-to-one name="myEnumeration" class="MyEnumeration" fetch="select">
<column name="EnumerationId" length="36" />
</many-to-one>
...
</hibernate-mapping>
The mapping above works in that I can now access MyEnumeration instances in my code and then get the EnumerationValue. However, I would like to abstract that. Instead, I would like to access the myEnumeration property as a string instead of 开发者_运维技巧a MyEnumeration class.
How can I do this with the Hibernate mapping file?
@Transient
public String getMyEnumerationValue() {
if (this.myEnumeration == null) {
return null;
}
else {
return this.myEnumeration.getValue();
}
}
A setter is more complicated, because it would need access to the session to get the ID of the enumeration having the given value (provided it's unique) in order to populate the myEnumeration
field.
精彩评论