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?
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
You can reference the class of your enum type in a @Type annotation on your entity attribute. This is a good approach if you only use the type on one entity attribute. When you use this mapping, Hibernate uses the EnumTypePostgreSql to map the Rating value to a PostgreSQL-specific enum type.
valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
The full name of HBM is Hibernate Mapping. It is an XML file in which we define the mapping between POJO class to the database table and POJO class variables to table columns. The resource file hibernate. cfg. xml, which supports to represent the Hibernate configuration information.
Here is the solution with Hibernate 3.6.x :
<class name="a.b.c.myObject" table="OBJECT">
<property name="myEnum" column="EXAMPLE">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">a.b.c.myEnum</param>
</type>
</property>
</class>
Similar to @monim answer, but more elegant way:
<class name="a.b.c.myObject" table="OBJECT">
<property name="myEnum" column="EXAMPLE">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">a.b.c.myEnum</param>
<param name="useNamed">true</param>
</type>
</property>
</class>
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>
Just editing @Emmanuel Bourg answer and adding another <param>
like this:
<class name="a.b.c.myObject" table="OBJECT">
<property name="myEnum" column="EXAMPLE">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">a.b.c.myEnum</param>
<param name="type">12</param>
</type>
</property>
</class>
12 is equivilant to java.sql.Types.VARCHAR
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With