7

I have the class Person mapped with annotations with enum Sex reffering to the sex if is male or female. Let's see:

@Entity
@Table(name = "PERSON")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Enumerated(EnumType.STRING)
    @Column(name = "SEX")
    private Sex sex;

    private enum Sex {
        M,
        F;
    } 

    // Getters, setters & constructors
}

When I test getting all the rows from the MySQL database, it works and the mapping is correct.

The database is already predefined, here is the column's definition:

`SEX` enum('M','F') NOT NULL

However the error occurs when I configure Hibernate with hibernate.hbm2ddl.auto=validate:

found [enum (Types#CHAR)], but expecting [varchar(255) (Types#VARCHAR)]

The error is a bit different (expecting [integer (Types#INTEGER)]) happend when I use EnumType.ORDINAL or no @Enumerated at all.

What do I do wrong?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183

1 Answers1

18

try add columnDefinition

@Enumerated(EnumType.STRING)
@Column(name = "SEX" , columnDefinition="ENUM('M','S')" ,nullable = false )
private Sex sex;

hibernate validate do check types , lenght.... as you have this in db level validator thinks it's different type .

I didn't see it with Oracle , but with MySql it's might be

xyz
  • 5,228
  • 2
  • 26
  • 35
  • 2
    It is verbose and it repeats the enum declaration at two places in the Java code. At this price I would not use in MySQL an enum as type but a varchar and would add a constraint on this column to specify the accepted values by. – davidxxx Jul 01 '17 at 19:54
  • Due to you map value form db into enum.in db you can update this value and your code stop work – xyz Jul 01 '17 at 19:55
  • 9
    Simply adding `@Column(columnDefinition = "enum")` appears to do the trick with H2. – Didier Breedt Jul 21 '18 at 10:31
  • 4
    Adding @Column(columnDefinition = "enum") does the trick also in the case of MySQL – Ahmad Khundaqji May 30 '19 at 13:43
  • 2
    Postgresql does not like @Column(columnDefinition = "enum"). any counterpart? – Andrew Jul 26 '20 at 19:47
  • Postgresql likes `@Column(columnDefinition = )` eg `@Column(columnDefinition = sex)` – Jan Dev Jul 01 '21 at 18:10