Mapping Java 5 enums with Hibernate

Hibernate is used to map java objects to a relational database. Ideally, you would like your java object model to be as object-oriented as possible. It is also nice to be able to use features like java 5 enums while coding the object model. In this tutorial, I’ll share with you how I ended up mapping a simple object model using java 5 enums into Hibernate.

I’ve found the best way to jumpstart yourself into using Hibernate is to go through the official tutorial on the Hibernate site.

A Simple Example

I have a Beer object that corresponds directly to a BEER table in a database. The Beer object can wither be an “Ale” or a “Lager”, and there may be more types in the future. So the database schema looks like this:

Simple Beer schema
+--------------------+
| BEER               |
+--------------------+           +----------------+
| NUMBER  | ID       |           | BEER_TYPE      |
| VARCHAR | BRAND    |           +----------------+
| NUMBER  | TYPE     | FK------- | NUMBER  | ID   |
| NUMBER  | VOLUME   |           | VARCHAR | NAME |
+--------------------+           +----------------+

It is pretty straightforward how to create a java class to represent this data. Ideally, I would like to use a java 5 enum object to keep track of the beer type, so I use it within my data object to specify type:

Beer Data Object
public class Beer {
    private BeerType type;
    private String brand;
    private double volume;

    public BeerType getType() {
        return type;
    }

    public void setType(BeerType type) {
        this.type = type;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getVolume() {
        return volume;
    }

    public void setVolume(double volume) {
        this.volume = volume;
    }
}

The BeerType enum will simply specify the type of beer for each Beer object. This enum is going to map directly to the BEER_TYPE table. So I’ve given each beer type its own id through the private internal enum constructor. There is an accessor method for hibernate to retrieve the id when it needs to do the mapping.

BeerType enum
public enum BeerType {
UNKNOWN(0), ALE(1), LAGER(2);private int id;private BeerType(int id) {
this.id = id;
}

public int getId() {
return id;
}

}

One of the first things I found when I started searching the internet for ways to map Java 5 enums to a database using Hibernate was this article on the Hibernate page. It shows an implementation of the Hibernate UserType in a way that will allow an enum to be used within a hibernate key mapping. So if I create a custom type definition in the key-mapping that uses the GenericEnumUserType class as the class, and passes in the actual BeerType enum classpath as a parameter, I can do the work to break out the enum details in the GenericEnumUserType implementation.

Hibernate key-mapping for Beer
<hibernate-mapping>
    <typedef name="beerType">
        <param name="enumClassName">net.dangertree.BeerType</param>
        <param name="identifierMethod">getId</param>
    </typedef>

    <class name="net.dangertree.Beer" table="BEER">
        <id name="id" type="int" column="ID">
            <generator/>
        </id>
        <property name="type" type="beerType" column="TYPE"/>
        <property name="brand" type="string" column="BRAND"/>
        <property name="volumn" type="double" column="VOLUME"/>
    </class>
</hibernate-mapping>

Here is the full code for the GenericEnumUserType class that I used to help map my enums into Hibernate. Reflection is used to find an “identifier” method in the enum that will get the id for each value. I have specified in the type-def in my key mapping that I’m going to use the getId() method of my enum to get an identifying attribute. By default, the class will look for the inherent name method of enum, but I’m using ids as my identifier.

The two method objects are grabbed and saved, then called in the null-safe setter and getter deeper within the Hibernate workings.

This class implementation of UserType is not exactly the same as any of those listings on the hibernate article I mentioned earlier. I had to make several minor changes to get it working with this code.
Generic Enum UserType implementation
import org.hibernate.HibernateException;
import org.hibernate.type.NullableType;
import org.hibernate.type.TypeFactory;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;import java.io.Serializable;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;public class GenericEnumUserType implements UserType, ParameterizedType {
private static final String DEFAULT_IDENTIFIER_METHOD_NAME = “name”;
private static final String DEFAULT_VALUE_OF_METHOD_NAME = “valueOf”;

private Class enumClass;
private Class identifierType;
private Method identifierMethod;
private Method valueOfMethod;
private NullableType type;
private int[] sqlTypes;

public void setParameterValues(Properties parameters) {
String enumClassName = parameters.getProperty(”enumClassName”);
try {
enumClass = Class.forName(enumClassName).asSubclass(Enum.class);
} catch (ClassNotFoundException cfne) {
throw new HibernateException(”Enum class not found”, cfne);
}

String identifierMethodName = parameters.getProperty(”identifierMethod”,
DEFAULT_IDENTIFIER_METHOD_NAME);

try {
identifierMethod = enumClass.getMethod(identifierMethodName,
new Class[0]);
identifierType = identifierMethod.getReturnType();
} catch (Exception e) {
throw new HibernateException(”Failed to obtain identifier method”,
e);
}

type = (NullableType) TypeFactory.basic(identifierType.getName());

if (type == null)
throw new HibernateException(”Unsupported identifier type ”
+ identifierType.getName());

sqlTypes = new int[] { type.sqlType() };

String valueOfMethodName = parameters.getProperty(”valueOfMethod”,
DEFAULT_VALUE_OF_METHOD_NAME);

try {
valueOfMethod = enumClass.getMethod(valueOfMethodName,
new Class[] { identifierType });
} catch (Exception e) {
throw new HibernateException(”Failed to obtain valueOf method”, e);
}
}

public Class returnedClass() {
return enumClass;
}

public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
Object identifier = type.get(rs, names[0]);
if (rs.wasNull()) {
return null;
}

try {
return valueOfMethod.invoke(enumClass, new Object[] { identifier });
} catch (Exception e) {
throw new HibernateException(”Exception while invoking ”
+ “valueOf method ‘” + valueOfMethod.getName() + “‘ of ”
+ ”enumeration class ‘” + enumClass + “‘”, e);
}
}

public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
try {
if (value == null) {
st.setNull(index, type.sqlType());
} else {
Object identifier = identifierMethod.invoke(value,
new Object[0]);
type.set(st, identifier, index);
}
} catch (Exception e) {
throw new HibernateException(”Exception while invoking ”
+ “identifierMethod ‘” + identifierMethod.getName() + “‘ of ”
+ ”enumeration class ‘” + enumClass + “‘”, e);
}
}

public int[] sqlTypes() {
return sqlTypes;
}

public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}

public Object deepCopy(Object value) throws HibernateException {
return value;
}

public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}

public boolean equals(Object x, Object y) throws HibernateException {
return x == y;
}

public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}

public boolean isMutable() {
return false;
}

public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}
}

Ok, there is only one problem now. The DEFAULT_VALUE_OF_METHOD_NAME method is specified by default to be valueOf, and I have not provided a parameter to override that in the type-def. So in order for my enum to match this, I need to add a valueOf method to my enum. And when the nullSafeGet method calls the “valueOfMethod“, it sends it an identifier as a parameter, so our valueOf method needs to take an int id as a parameter.

Modified BeerType enum
public enum BeerType {
UNKNOWN(0), ALE(1), LAGER(2);private int id;private BeerType(int id) {
this.id = id;
}

public int getId() {
return id;
}

public static BeerType valueOf(int id) {
switch (id) {
case 1: return ALE;
case 2: return LAGER;
default: return UNKNOWN;
}
}

}

Now I have my data object, the enum it is using, my key-mapping, and an implementation of UserType that provides a way to access the enum through a type-def element in the key-mapping.

One thought on “Mapping Java 5 enums with Hibernate

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s