mybatis-plus 枚举 作为 json 存入 数据库字段 查询出来自定义映射

15 阅读1分钟
JacksonTypeHandler 查询时,json 映射到 枚举,报错,追源码没找到问题。
先用下面的方式解决

参考: juejin.cn/post/732021…

image.png

@JsonFormat(shape = JsonFormat.Shape.OBJECT) 
@Getter
@AllArgsConstructor
public enum FdsPoolEnum {

    aigcContent1("aigcContent1", "01", "aigc_content_1"),
    aigcContent3("aigcContent3", "03", "aigc_content_3");

    @EnumValue
    private final String name;
    private final String code;
    private final String url;


    public static FdsPoolEnum fromValue(String value) {
        ObjectMapper mapper = new ObjectMapper();
        for (FdsPoolEnum fdsPoolEnum : values()) {
            try {
                if (mapper.writeValueAsString(fdsPoolEnum).equalsIgnoreCase(value)) {
                    return fdsPoolEnum;
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        throw new IllegalArgumentException("Unknown enum value: " + value);
    }

//@JsonFormat(shape = JsonFormat.Shape.OBJECT) 这行的作用是 前端传来 aigcContent1 ,直接转成 {"name":"aigcContent1","code":"01","url":"aigc_content_1"} , fromValue(String value) 中的 value 就是这个 json ,equalsIgnoreCase 就能匹配上,不然的话 value 是 “aigcContent1” ,就匹配不上

image.png image.png

typeHandler = FdsPoolEnumTypeHandler.class
package com.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class FdsPoolEnumTypeHandler extends BaseTypeHandler<FdsPoolEnum> {

    // 将Java类型转换为数据库类型
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, FdsPoolEnum parameter, JdbcType jdbcType) throws SQLException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            ps.setString(i, mapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    // 从数据库类型转换为Java类型
    @Override
    public FdsPoolEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return value == null ? null : FdsPoolEnum.fromValue(value);
    }

    @Override
    public FdsPoolEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return value == null ? null : FdsPoolEnum.fromValue(value);
    }

    @Override
    public FdsPoolEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return value == null ? null : FdsPoolEnum.fromValue(value);
    }
}