【问题标题】:InvalidDataAccessApiUsageException: No enum constantInvalidDataAccessApiUsageException:没有枚举常量
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您的数据库包含一个角色 = 2 的条目。

    确保数据库中的条目与 Enum 中的值相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2015-11-17
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 2015-08-21
      相关资源
      最近更新 更多