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?
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.
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