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>
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!