O'Reilly logo

Harnessing Hibernate by James Elliott, Ryan Fowler, Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with Persistent Enumerations

You may have noticed that we never defined a persistence mapping for the SourceMedia class in the first part of this chapter. That’s because our enumerated type is a value that gets persisted as part of one or more entities, rather than being an entity unto itself.

In that light, it’s not surprising that we’ve not yet done any mapping. That happens when it’s time to actually use the persistent enumeration—which is to say, now.

How do I do that?

Recall that we wanted to keep track of the source media for the music tracks in our jukebox system. That means we want to use the SourceMedia enumeration in our Track mapping. We can simply add a new property tag to the class definition in Track.hbm.xml, as shown in Example 6-3.

Example 6-3. Adding the sourceMedia property to the track mapping document

...
<property name="volume" type="short">
  <meta attribute="field-description">How loud to play the track</meta>
</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>

<set name="comments" table="TRACK_COMMENTS">
...

Notice that we’ve told Hibernate that the type of this property is our UserType implementation, not the raw enumeration type that it is responsible for helping persist. Because the type of our sourceMedia property names a class that implements the UserType interface, Hibernate knows to delegate ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required