如何让JPA存储枚举的自定义属性值而非枚举名称?
问题
我定义了如下枚举:
public enum AccountType { CURRENT_ACCOUNT("currentAccount"), private final String name; AccountType(String name) { this.name = name; } @JsonValue public String getName() { return name; } @Override public String toString() { return getName(); } }
实体类中的字段标注如下:
@Column(name = "account_type", nullable = false) @Enumerated(EnumType.STRING) private AccountType accountType;
但将数据保存到数据库时,存储的是枚举名称“CURRENT_ACCOUNT”而非枚举的自定义属性值“currentAccount”,请问该如何设置才能存储“currentAccount”?
解决方案
JPA的@Enumerated(EnumType.STRING)默认只会存储枚举的名称,要存储自定义属性值,最通用的方案是实现JPA标准的AttributeConverter接口,手动处理枚举与数据库字段的双向转换:
步骤1:实现属性转换器
创建转换器类,负责枚举和数据库存储字符串的转换逻辑:
import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter(autoApply = true) // 自动应用到所有AccountType类型的字段 public class AccountTypeConverter implements AttributeConverter<AccountType, String> { // 将枚举转换为数据库存储的字符串 @Override public String convertToDatabaseColumn(AccountType attribute) { return attribute != null ? attribute.getName() : null; } // 将数据库字符串转换为枚举实例 @Override public AccountType convertToEntityAttribute(String dbData) { if (dbData == null) { return null; } // 遍历枚举值匹配自定义属性值 for (AccountType type : AccountType.values()) { if (type.getName().equals(dbData)) { return type; } } throw new IllegalArgumentException("无法识别的账户类型:" + dbData); } }
步骤2:修改实体类字段注解
移除原来的@Enumerated(EnumType.STRING)注解,转换器会接管转换逻辑:
@Column(name = "account_type", nullable = false) private AccountType accountType;
如果不想全局自动应用转换器(即autoApply=true),也可以单独在字段上指定转换器:
@Column(name = "account_type", nullable = false) @Convert(converter = AccountTypeConverter.class) private AccountType accountType;
内容的提问来源于stack exchange,提问作者dovexz12323
相关产品推荐
相关产品推荐

