7.2. Using a Custom Type Mapping

All right, we've created a custom type persistence handler, and it wasn't so bad! Now it's time to actually use it to persist our enumeration data the way we want it.

7.1.1. How do I do that?

This is actually almost embarrassingly easy. Once we've got the value class, SourceMedia, and the persistence manager, SourceMediaType, in place, all we need to do is modify any mapping documents that were previously referring to the raw value type to refer instead to the custom persistence manager.

In our case, that means we change the mapping for the mediaSource property in Track.hbm.xml so it looks like Example 7-2 rather than Example 6-3.

That's it. No, really!.

Example 7-2. Custom type mapping for the sourceMedia property
<property name="sourceMedia" type="com.oreilly.hh.SourceMediaType">
  <meta attribute="field-description">Media on which track was obtained</meta>
  <meta attribute="use-in-tostring">true</meta>
</property>

At this point, running ant schema will rebuild the database schema, changing the SOURCEMEDIA column in the TRACK table from integer to VARCHAR(as specified by SourceMediaType's sqlTypes() method).

Thanks to the beauty of letting the object/relational mapping layer handle the details of how data is stored and retrieved, we don't need to change any aspect of the example or test code that we were using in Chapter 6. You can run ant ctest to create sample data. It will run with no complaint. If you fire up ant db to look at the way it's stored, ...

Get Hibernate: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.