Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL enum with hibernate

Tags:

java

hibernate

I have a database table using an enum. This is already working with hibernate (using XML), and I'm trying to convert it to annotations as this is one of the last pieces to still be using xml notation.

The column definition:

enum('Active','Pending','Cancelled','Suspend')

The following works:

<property
    name="status"
    column="STATUS"
    type="string"
    not-null="true" />

This does not work:

@Column(name = "status")
public String status;

The annotation-style leads to the following exception upon startup: org.hibernate.HibernateException: Wrong column type in UserDTO for column status. Found: enum, expected: varchar(255)

Is there any way for me to force this to accept a String as it did using the XML notation?

like image 320
Jesse Avatar asked Jul 02 '09 20:07

Jesse


People also ask

How are enums stored in database?

First of all, in order to save enum values in a relational database using JPA, you don't have to do anything. By default, when an enum is a part of an entity, JPA maps its values into numbers using the ordinal() method. What it means is that without customizations JPA stores enum value as numbers.

What is the use of @enumerated annotation?

Annotation Type Enumerated. Specifies that a persistent property or field should be persisted as a enumerated type. The Enumerated annotation may be used in conjunction with the Basic annotation, or in conjunction with the ElementCollection annotation when the element collection value is of basic type.

What is Enumtype ordinal?

ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum.


1 Answers

I figured it out. It should be:

@Column(name="status", columnDefinition="enum('Active','Pending','Cancelled','Suspend')")
public String status;
like image 125
Jesse Avatar answered Sep 23 '22 23:09

Jesse