Home > Database > Mysql Tutorial > How to Preserve Enum Type in MySQL Database with Hibernate?

How to Preserve Enum Type in MySQL Database with Hibernate?

Mary-Kate Olsen
Release: 2024-10-30 19:40:03
Original
826 people have browsed it

How to Preserve Enum Type in MySQL Database with Hibernate?

Enum in Hibernate: Preserving Enum Type in MySQL Database

When defining an enum field in an entity intended to map to a database, developers may face issues with Hibernate expecting an integer data type while the enum column is defined as an enum in the database. To resolve this conflict, one must explicitly inform Hibernate to treat the column as an enum rather than an integer.

In the given example, an enum "com.mydomain.myapp.enums.Gender" has been created to represent the "gender" attribute of a "Person" entity. However, attempts to persist this enum type in the database result in the error: "Wrong column type in MyApp.Person for column Gender. Found: enum, expected: integer."

To address this issue, Hibernate must be provided with the correct column definition explicitly. This can be achieved by annotating the "gender" field with both the "@Column" and "@Enumerated" annotations, specifying the column definition as an enum and the enum type as a string. Here's an illustration:

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

By explicitly providing this column definition, Hibernate will no longer attempt to guess the data type. This approach ensures that the enum type is preserved in the MySQL database, allowing the mapping to function correctly.

The above is the detailed content of How to Preserve Enum Type in MySQL Database with Hibernate?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template