Home  >  Article  >  Database  >  How to Preserve Enum Type in Hibernate When Working with MySQL\'s `enum` Column?

How to Preserve Enum Type in Hibernate When Working with MySQL\'s `enum` Column?

DDD
DDDOriginal
2024-10-31 11:28:29304browse

How to Preserve Enum Type in Hibernate When Working with MySQL's `enum` Column?

Enum Persistence in Hibernate: Preserving Enum Type

Problem

Consider the following setup: a MySQL table with a column defined as "gender enum('male', 'female')", a corresponding Java enum "Gender", and a Person entity with "Gender gender". When attempting to boot the application, an error is encountered: "Wrong column type in MyApp.Person for column Gender. Found: enum, expected: integer."

Cause and Solution

By default, Hibernate expects enumerated fields to be stored as integers. To specify that the enum type should be maintained in the database, use the following annotations:

<code class="java">@Column(columnDefinition = "enum('MALE','FEMALE')")
@Enumerated(EnumType.STRING)
private Gender gender;</code>

Alternatively, if you prefer to delegate schema generation to Liquibase or an SQL script, you can provide a dummy value for the columnDefinition:

<code class="java">@Column(columnDefinition = "enum('DUMMY')")
@Enumerated(EnumType.STRING)
private ManyValuedEnum manyValuedEnum;</code>

This ensures that Hibernate will rely on the Java enum and the database schema synchronization tools to maintain the correct enum values.

The above is the detailed content of How to Preserve Enum Type in Hibernate When Working with MySQL\'s `enum` Column?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn