如何配置JPA将所有枚举默认映射为String类型?
Great question—forgetting @Enumerated(EnumType.STRING) and ending up with ordinal-based enum mappings is such a common headache! The good news is you absolutely can set EnumType.STRING as the default for all your JPA enums, so you don’t have to annotate every single enum field manually. Here’s how to do it based on your JPA provider:
For Hibernate (Most Common JPA Provider)
Hibernate has a built-in global property that lets you set the default enum mapping type.
If you’re using Spring Boot
Add this line to your application.properties or application.yml:
spring.jpa.properties.hibernate.type.enum.default=STRING
If you’re using a standard persistence.xml
Add the property inside your persistence unit configuration:
<persistence-unit name="yourPersistenceUnitName"> <!-- ... other configs ... --> <properties> <property name="hibernate.type.enum.default" value="STRING"/> </properties> </persistence-unit>
For EclipseLink
EclipseLink also supports global enum configuration via a persistence property:
<persistence-unit name="yourPersistenceUnitName"> <!-- ... other configs ... --> <properties> <property name="eclipselink.persistence-context.properties.enum-type" value="STRING"/> </properties> </persistence-unit>
Important Note
This global setting won’t override explicit @Enumerated annotations. If you ever need a specific enum field to use EnumType.ORDINAL, just add @Enumerated(EnumType.ORDINAL) to that field—it will take precedence over the default.
内容的提问来源于stack exchange,提问作者Vlad Dinulescu

