Mybatis-Plus 实现 jsonb类型的数据存取

1、自定义类型处理器

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

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

public class JSONTypePgHandler<T extends Object> extends BaseTypeHandler<T> {
    private static final PGobject jsonObject = new PGobject();
    private Class<T> clazz;

    public JSONTypePgHandler(Class<T> clazz) {
        if (clazz == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        jsonObject.setType("json");
        jsonObject.setValue(this.toJson(parameter));
        ps.setObject(i, jsonObject);
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName), clazz);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex), clazz);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex), clazz);
    }

    private String toJson(T object) {
        try {
            return JSON.toJSONString(object, SerializerFeature.WriteNullListAsEmpty);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private T toObject(String content, Class<?> clazz) {
        if (content != null && !content.isEmpty()) {
            try {
                return (T) JSON.parseObject(content,clazz);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }
}

2、存储:字段上添加处理器

    @Schema(description = "当前处理人")
    @TableField(value = "current_handler", typeHandler = JSONTypePgHandler.class)
    private List<Handler> currentHandler;

3、读取:①、设置autoResultMap = true,自动为实体类生成一个结果映射;②、xml文件定义映射,数据库结果集中获取数据映射到Java对象的属性

@TableName(value = "tb_report_info",autoResultMap = true)
public class ReportInfo {}
    <resultMap id="ReportInfo" type="com.tdar.entity.ReportInfo">
        <result property="currentHandler" column="current_handler" javaType="java.util.List" typeHandler="com.tdar.utils.JSONTypePgHandler"></result>
    </resultMap>

 

posted on 2024-05-28 17:20  LJD泊水  阅读(191)  评论(0编辑  收藏  举报