博客程序目前完成了数据库模型搭建,目前处于Spring Data Jpa框架的接入,由于我们系统很多数据库字段都需要使用到枚举,这个时候我们需要将枚举类型接入JPA的注解,JPA的注解@Enumerated只能将枚举的次序和原始name值插入数据库中,不适合于日后业务变化后的调用(插入一个枚举或者修改枚举值,都会在数据库出现脏数据,影响修改之前数据)
所以需要寻找一个自定义的方式进行,所幸jpa规范2.2提供了一个属性转换器,
AttributeConverter来进行转换

@Converter(autoApply = true)
public class CommentStatusConverter implements AttributeConverter<CommentStatus, Integer> {


    /**
     * Converts the value stored in the entity attribute into the data representation to be stored
     * in the database.
     *
     * @param attribute the entity attribute value to be converted
     * @return the converted data to be stored in the database column
     */
    @Override
    public Integer convertToDatabaseColumn(CommentStatus attribute) {
        return Optional.ofNullable(attribute).map(CommentStatus::getCode)
            .orElseThrow(() -> new IllegalArgumentException("CommentStatus is null"));
    }

    /**
     * Converts the data stored in the database column into the value to be stored in the entity
     * attribute. Note that it is the responsibility of the converter writer to specify the correct
     * <code>dbData</code> type for the corresponding column for use by the JDBC driver: i.e.,
     * persistence providers are not expected to do such type conversion.
     *
     * @param dbData the data from the database column to be converted
     * @return the converted value to be stored in the entity attribute
     */
    @Override
    public CommentStatus convertToEntityAttribute(Integer dbData) {
        return Arrays.stream(CommentStatus.values())
            .filter(status -> Objects.equals(status.getCode(), dbData))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("CommentStatus is null"));
    }
}

这里我们写一个测试程序测试一下是否能插入

    @Test
    void testEnum2Repository() {
        var comments = new Comments();
        comments.setComment("测试评论2");
        comments.setStatus(CommentStatus.SPAM_COMMENTS);
        entityManager.persist(comments);
        assertThat(comments.getStatus().getCode()).isEqualTo(CommentStatus.SPAM_COMMENTS.getCode());
    }

image-1656506777438
表示我们的功能是有效的

Q.E.D.