【发布时间】:2020-04-20 00:50:16
【问题描述】:
我有一个 Role 枚举,像这样:
public enum Role{
admin('a'),
member('m'),
pending('p');
char role;
Role(char a) {
this.role = a;
}
public char getRole() {
return role;
}
public static Role getByRole(char role) {
return Arrays.stream(Role.values())
.filter(Role -> Role.getRole() == role)
.findFirst()
.orElse(Role.pending);
}
}
为了支持转换,我创建了一个名为 RoleConverter 的类:
@Converter
public class RoleConverter implements AttributeConverter<Role, Character> {
@Override
public Character convertToDatabaseColumn(Role Role) {
return Role.getRole();
}
@Override
public Role convertToEntityAttribute(Character dbData) {
System.out.println(dbData);
return Role.getByRole(dbData);
}
}
在我的目标对象中,我添加了适当的注释:
@Convert(converter = RoleConverter.class)
@Enumerated(EnumType.STRING)
public Role role;
它仍然给我错误 - 嵌套异常是 org.springframework.dao.InvalidDataAccessApiUsageException: No enum constant com.mua.cse616.model.Role.2;
在 h2 和 jpa 中使用 spring
【问题讨论】:
-
似乎您的数据库中有一行在列中具有值 2,而 obv 在枚举中不存在。也许您一开始没有 @Enumerated 注释,因此 JPA 使用序数作为列值。
-
@RobertNiestroj 我删除了旧数据库,现在一切正常,您可以将其发布为答案吗?
标签: spring spring-boot jpa spring-data-jpa h2