Home  >  Article  >  Database  >  How to Persist Enum Types in Hibernate?

How to Persist Enum Types in Hibernate?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 19:59:30680browse

How to Persist Enum Types in Hibernate?

Persisting Enum Types in Hibernate

When working with Hibernate, mapping enum types to database columns can sometimes pose a challenge. By default, Hibernate expects enum values to be stored as integers. However, you may prefer to maintain the enum type in the database for clarity or consistency.

To achieve this, you can leverage the @Column annotation with the columnDefinition attribute:

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

By specifying the columnDefinition, you explicitly define the data type of the column in the database, ensuring that the enum type is preserved.

If you're not reliant on Hibernate for schema generation, you can further simplify the process by using an arbitrary value for the columnDefinition:

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

This approach allows you to keep your Java enum and database schema in sync without relying on hard-coded values.

The above is the detailed content of How to Persist Enum Types in Hibernate?. 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