【问题标题】:Is it possible to define how an enum is (de-)serialized for persistence inside the enum?是否可以定义枚举如何(反)序列化以实现枚举内部的持久性?
【发布时间】:2021-04-19 15:45:03
【问题描述】:

我有一个使用 JPA 和休眠的 Spring Boot 项目。

假设有一个枚举 Code 代表一个简单的 http 状态码:

public enum Code {
  OK,
  NOT_FOUND
}

假设这个枚举有一个转换器,称为CodeConverter

@Converter
public class CodeConverter implements AttributeConverter<Code, Integer> {
  @Override
  public Integer convertToDatabaseColumn(Code code) {
    if (code == Code.OK) return 200;
    if (code == Code.NOT_FOUND) return 404;
    return null;
  }

  @Override
  public Code convertToEntityAttribute(Integer integer) {
    if (integer == 200) return Code.OK;
    if (integer == 404) return Code.NOT_FOUND;
    return null;
  }
}

在不知道哪些实体使用Code 的情况下,我可以在Code 中指定Code 应该始终使用CodeConverter 进行(反)序列化吗? 例如:

@UseConverter(CodeConverter.class)
public enum Code {
...

我知道CodeConverter@Converter(autoApply = true) 注释,但是仅当CodeConverter 在Spring Boot 配置中被@EntityScan 扫描时才有效。对于我的用例,我不能依赖这个。

【问题讨论】:

    标签: java spring-boot hibernate jpa spring-data-jpa


    【解决方案1】:

    根据您使用的 JPA 版本,您可以考虑使用 @PostLoad@PrePersist 进行所需的翻译:

    这篇文章展示了一个很好的例子: https://www.baeldung.com/jpa-persisting-enums-in-jpa

    【讨论】:

    • PostLoadPrePersist 必须在实体上进行注释,对吗?在我的用例中,我不知道使用 Code 的实体。 Code 本身不是一个实体,它只是一个枚举,将成为某些实体的一部分。但是,在我的用例中,这些实体仍然未知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2023-02-22
    • 2019-05-31
    相关资源
    最近更新 更多