首页 > 解决方案 > InvalidDataAccessApiUsageException:没有枚举常量

问题描述

我有一个角色枚举,如下所示:

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

标签: springspring-bootjpaspring-data-jpah2

解决方案


似乎您的数据库中有一行,其列中的值 2 显然不存在于枚举中。也许您一开始没有@Enumerated注释,因此 JPA 使用序数作为列值。


推荐阅读