mybatisplus实体映射json List泛型

现象

直接用默认的是不行的,虽然查询没有问题,但是对List操作会报类型转换错误

方案

  • 自定义转换器
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARBINARY)
@MappedTypes( {List.class})
public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int parameterIndex, List<T> parameter, JdbcType jdbcType)
            throws SQLException {
        String content = CollUtil.isEmpty(parameter) ? null : JSONObject.toJSONString(parameter);
        preparedStatement.setString(parameterIndex, content);
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return this.getListByJsonArrayString(resultSet.getString(columnName));
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return this.getListByJsonArrayString(resultSet.getString(columnIndex));
    }

    @Override
    public List<T> getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return this.getListByJsonArrayString(callableStatement.getString(columnIndex));
    }

    private List<T> getListByJsonArrayString(String content) {
        return StrUtil.isBlank(content) ? new ArrayList<>() : JSONObject.parseObject(content, this.specificType());
    }

    /**
     * 具体类型,由子类提供
     *
     * @return 具体类型
     */
    protected abstract TypeReference<List<T>> specificType();
}

import com.alibaba.fastjson2.TypeReference;
import com.bbibm.common.typehandler.ListTypeHandler;
import com.bbibm.defensearea.domain.entity.DefenseArea;

import java.util.List;

public class DistanceInfoListTypeHandler extends ListTypeHandler<DefenseArea.DistanceInfo> {
    @Override
    protected TypeReference<List<DefenseArea.DistanceInfo>> specificType() {
        return new TypeReference<List<DefenseArea.DistanceInfo>>() { };
    }
}
  • 使用方式
@TableField(typeHandler = DistanceInfoListTypeHandler.class)
private List<DistanceInfo> dasBindingDistance;
posted @ 2026-01-23 13:10  四码难追  阅读(11)  评论(0)    收藏  举报