Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a MySQL enum to a Java Enum with JPA? [duplicate]

I have a MySQL table using MySQL-native enum values:

CREATE TABLE users (
  id int NOT NULL AUTO_INCREMENT,
  status enum('PENDING', 'ACTIVE', 'INACTIVE') NOT NULL
);

I want to access this in Spring Boot through JPA, so I modelled it as an entity with an enum attribute.

public enum Status {
    PENDING,
    ACTIVE,
    INACTIVE;
}

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column
    private int id;

    @Column
    @Enumerated(EnumType.STRING)
    private Status status;

    /* Getters, Setters,… */
}

When I start my application I experience with ddl-auto property set to validate I expect an error with schema validation:

org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [status] in table [users]; found [enum (Types#CHAR)], but expecting [varchar(255) (Types#VARCHAR)]

What do I have to do work in JPA with MySQL enums?

like image 799
bfncs Avatar asked May 22 '19 13:05

bfncs


1 Answers

To make Hibernate work correctly with native MySQL enum columns, you need to give it an explicit hint of the correct DDL for the column instead of letting it defer the type. You can do this by defining columnDefinition for the column in your entity:

public enum Status {
    PENDING,
    ACTIVE,
    INACTIVE;
}

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column
    private int id;

    @Column(columnDefinition = "ENUM('PENDING', 'ACTIVE', 'INACTIVE')")
    @Enumerated(EnumType.STRING)
    private Status status;

    /* … */
}

This also applies if you use AttributeConverters to map your MySQL enum to a Java enum.

like image 114
bfncs Avatar answered Oct 13 '22 20:10

bfncs