How to Preserve Enum Type in MySQL Database with Hibernate?
Oct 30, 2024 pm 07:40 PMEnum 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>
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

Run MySQl in Linux (with/without podman container with phpmyadmin)

What is SQLite? Comprehensive overview

Running multiple MySQL versions on MacOS: A step-by-step guide

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)?

How do I configure SSL/TLS encryption for MySQL connections?
