It’s all systems go at work at the moment, so not much time free to blog. I’m keen however, to post at least once this week so I thought I might just write quickly about a subject that most seasoned hibernate developers are probably well-aware of, but newbies might find useful :).

On occasion when developing your hibernate entities you might find a requirement to include a Java enumerated type as a property on one of the entities. For instance in the example below:

@Entity
@Table(name="myentity")
public Class MyEntity
{
private int id;
private MyEnum myEnum;
}

public enum MyEnum
{
ENUMVALUE1, ENUMVALUE2;
}

To facilitate this the Java Persistance API (JPA) provides us with an @Enumerated annotation which we can use to markup the myEnum field in our entity above, like so:

 private MyEnum myEnum;
@Column(name="myenum")
@Enumerated(EnumType.ORDINAL)
public MyEnum getMyEnum()
{
return myEnum
}

The EnumType enum property of the @Enumerated annotation allows us to specify in what form the enum is persisted to the database. EnumType.ORDINAL specifies that the enum will be persisted as an integer value. In the above example, setting myEnum to MyEnum. ENUMVALUE1 will persist as 0, ENUMVALUE2 as 1 etc.

The alternative to this is to use EnumType.STRING, which will persist the name of enum value that the field is currently set to. So using the example above, setting the myEnum field to MyEnum. ENUMVALUE1 will persist as ‘ENUMVALUE1′, ‘ENUMVALUE2′ as ‘ENUMVALUE2′ etc.

Note: if you use EnumType.ORDINAL hibernate will create an integer column for the field, if you use EnumType.STRING then hibernate will create a varchar column for the field (in MySQL at least). If you decide to swap from ORDINAL to STRING then you will need to either change the column definition in the database yourself, or drop the column and allow hibernate to recreate it with it’s new datatype.

Once you’ve sucessfully setup your entity with one or more enum fields then it’s very straightforward to write queries (or perform any usual data operations) utilitising these fields. For example, to return a list of all entities MyEntity entities whoose myEnum property is set to ENUMVALUE2 we can just write:

Criteria crit = getSession().createCriteria(MyEntity.class);
crit.add(Restrictions.eq("myEnum", MyEnum.ENUMVALUE2))
List<MyEntity> = crit.list();

The EnumType we’ve specified for the field is effectively transparent and makes no difference at all when it comes to writing quries like this. I hope this has been a useful (if brief) explanation of enums and hibernate.