views:

417

answers:

3

I am trying to create a class in HBM file which contains an Enum as a field.

The HBM is similar to this:

<class name="a.b.c.myObject" table="OBJECT" >
       <property name="myEnum" column="EXAMPLE" type="a.b.c.myEnum" />
</class>

and let's say that this is the Enum:

public enum myEnum{
    a, b, c;
}

The problem is that in the DB I expected to see the String value of that enum (a,b or c) but instead I got the raw data of that field.

How can I solve that?

A: 

You need to use a UserType to persist that efficiently: https://www.hibernate.org/265.html

cherouvim
This is a rather outdated approach; creating all those extra custom types is unnecessary.
ChssPly76
@ChssPly76: You are right. Still using JDK 1.4 here.
cherouvim
+3  A: 

1) Easy solution: use Hibernate Annotations instead of XML-based mappings. Enum support is built-in:

@Entity
public class MyObject {
  @Enumerated(EnumType.STRING)
  @Column(name="EXAMPLE")
  private MyEnum myEnum;
}

2) If you can't use annotations, you can still use the EnumType they provide in XML-based mappings. You do need to have appropriate hibernate-annotations.jar in your classpath during deployment but there's no compile-time dependency:

<class name="a.b.c.myObject" table="OBJECT" >
  <property name="myEnum" column="EXAMPLE" type="org.hibernate.type.EnumType"/>
</class>
ChssPly76
I have tried the second option but it does the same.
Avi Y
"Does the same" meaning what? What did you mean by "raw data of the field" being stored in the database? Note that "type" attribute above must point to an actual Hibernate type; not to your enum class like you've specified in the question. The latter is illegal.
ChssPly76
+1  A: 

For reasons that remain obscure, the Hibernate developers insist on keeping the Hibernate core compatible with pre-Java5, and that means no enum support. When you try to persist an Enum field, it just serializes it, and you get binary data.

If you want to persist enums using an .hbm mapping configuration, you have to create and configure a custom UserType for each enum type you want to handle, which is tedious and irritating. The Hibernate documentation wiki has plenty of examples, many of which seem to contradict each other, and some of which even work.

If you use Hibernate annotations, though, you get full java5 support, including automatic handling of java5 enums. It's just a real shame that you have to do one or the other.

skaffman