Home > Database > Mysql Tutorial > body text

How to Persist Enums as Strings in Hibernate with @Column(columnDefinition) and @Enumerated(EnumType.STRING)?

Susan Sarandon
Release: 2024-10-30 04:47:02
Original
255 people have browsed it

How to Persist Enums as Strings in Hibernate with @Column(columnDefinition) and @Enumerated(EnumType.STRING)?

Hibernate Enum Persistence as an Enum

When defining an enum in a Hibernate entity, it's important to ensure that the persistence mechanism aligns with the database column's data type. In your case, the database column "gender" is defined as an enum type with values 'male' and 'female'.

The issue you're encountering might be due to a mismatch between the data types expected by Hibernate and the actual data type of the database column. By default, Hibernate expects enum values to be persisted as integers, but your database column is defined as an enum.

To resolve this discrepancy, you can explicitly instruct Hibernate to persist the enum as a string value by using the @Column(columnDefinition) annotation. This annotation defines the DDL (Data Definition Language) used to create the column. In your case, you can specify the column definition as:

@Column(columnDefinition = "enum('male','female')")
Copy after login

Additionally, you must annotate the enum field with @Enumerated(EnumType.STRING) to indicate that the enum should be persisted as a string value.

This updated code snippet should fix the issue:

@Column(columnDefinition = "enum('male','female')")
@Enumerated(EnumType.STRING)
private Gender gender;
Copy after login

By specifying the column definition and the enum type explicitly, you force Hibernate to persist the enum as a string, matching the data type of your database column. This will prevent the error you were encountering and ensure correct persistence of the enum data.

The above is the detailed content of How to Persist Enums as Strings in Hibernate with @Column(columnDefinition) and @Enumerated(EnumType.STRING)?. 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