【问题标题】:org.springframework.dao.InvalidDataAccessApiUsageException: Unknown name value [-1] for enum class in HIbernateorg.springframework.dao.InvalidDataAccessApiUsageException:HIbernate 中枚举类的未知名称值 [-1]
【发布时间】:2021-02-18 17:45:42
【问题描述】:

我正在尝试创建一个值为 1,-1,0 的枚举,但在映射数据时,-1 的未知序数值即将到来。下面是 enum 的一段代码。如何使用枚举来检索 -1 的序数值

@RequiredArgsConstructor
public enum Number {
    MULTIPLE(0, -1, "MULTIPLE"),
    ZERO(1, 0, "ZERO"),
    ONE(2, 1, "ONE");

    private static final Map<Integer, Number> DOCUMENT_CARDINALITY_ID = Arrays.stream(values())
            .collect(Collectors.toMap(Number :: intValue, Function.identity()));

    private static final Map<String, Number> DOCUMENT_CARDINALITY_BY_CODE = Arrays.stream(values())
            .collect(Collectors.toMap(Number :: toString, Function.identity()));

    private final int value;
    private final int id;
    private final String code;

    public static Number of(int id) {
        isTrue(DOCUMENT_CARDINALITY_ID.containsKey(id), "the id " + id + " is not valid!");
        return DOCUMENT_CARDINALITY_ID.get(id);
    }

    public static Number of(String code) {
        notNull(code, "the code is null!");
        isTrue(DOCUMENT_CARDINALITY_BY_CODE.containsKey(code), "the code " + code + " is not valid!");
        return DOCUMENT_CARDINALITY_BY_CODE.get(code);
    }

    public int intValue() {
        if (id == -1) {
            return 0;
        } else if (id == 0) {
            return 1;
        } else {
            return 2;
        }
    }

    @Override
    public String toString() {
        return code;
    }
}

【问题讨论】:

    标签: java spring spring-boot hibernate spring-mvc


    【解决方案1】:

    您不能设置 Enum 的序数值。序数值是根据其在 Enum 声明期间的位置设置的。在这种情况下,序数可能看起来像

    0 多个

    1 零

    2个

    有关详细信息,请参阅this 以前的帖子。此外,您的 spring 错误发生在此类之外,因此,我不知道是什么触发了它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多