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

Using a Custom Type Mapping

As noted in the introduction to this chapter, we are going to create a class that Hibernate can use when it needs to persist our enumeration. We’ll call our new class SourceMediaType. Our next decision is whether it needs to implement UserType or CompositeUserType. The reference documentation doesn’t provide much guidance on this question, but the API documentation confirms the hint contained in the interface names: the CompositeUserType interface is only needed if your custom type implementation wants to expose internal structure in the form of named properties that can be accessed individually in queries (as in our ZIP code example). For SourceMedia, a simple UserType implementation is sufficient. The source for a mapping manager meeting our needs is shown in Example 6-2.

Example 6-2. SourceMediaType.java, our custom type mapping handler

package com.oreilly.hh; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.usertype.UserType; /** * Manages persistence for the {@link SourceMedia} typesafe enumeration. */ public class SourceMediaType implements UserType { /** * Indicates whether objects managed by this type are mutable. * * @return <code>false</code>, since enumeration instances are immutable * singletons. */ public boolean isMutable() { return false; } /** * Return ...

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