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!