解决org.hibernate.type.descriptor.java.EnumJavaTypeDescriptor.fromOrdinal错误,需使用javax.persistence.Converter。在Spring Boot应用中,将数据库的INT值映射回枚举UserRole时,因枚举ID从1开始而非0,导致读取顺序值出错。通过在User POJO中添加@Convert注解,并在UserRole中实现AttributeConverter接口,解决了数据库值与枚举值的映射问题。具体代码示例如下:
@Convert(converter = UserRole.UserRoleConverter.class)
@Column(name = "ROLE")
@NotNull(message = "Role is required")
@JsonAlias("roleId")
private UserRole roleId;@Converter(autoApply = true)
public static class UserRoleConverter implements AttributeConverter<UserRole, Integer> {
@Override
public Integer convertToDatabaseColumn(UserRole attribute) {
if (attribute == null) {
throw new BadRequestException("Please provide a valid User Role.");
}
return attribute.getId();
}
@Override
public UserRole convertToEntityAttribute(Integer dbData) {
return UserRole.valueOf(dbData);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。