Friday, January 26, 2007

Hibernate - map column to a non-existent java property

On rare occasions, I had to populate a database column that doesn't have a matching property in the object model. Say, I have a not null column INTERFACE_ID and value for this column is derived based on some logic. Here is how I worked around it in Hibernate.

1. Create implementation of a UserType that has logic to derive a value for interface_id
2. Use the following mapping

<property name="interfaceId" column="INTERFACE_ID" access="noop" update="false" null="false" type="SomeUserTypeImplementation"/>

3. A few things to note...
⇒ name attribute is any madeup value
⇒ acces="noop" tells hibernate not to look for an object property for this column
⇒ not-null="false". noop columns must be defined as nullable
⇒ update="false". noop columns cannot be updated

No comments: