could not be found for the javaType (com.alibaba.fastjson.JSONObject) : jdbcType (null) combination

could not be found for the javaType (com.alibaba.fastjson.JSONObject) : jdbcType (null) combination

数据库使用JSON字段,mybatis错误

目前mysql5.7已经支持了JSON属性的字段。但是在使用mybatis对这种类型的字段进行接取的时候,会发现jdbcYype中并没有JSON属性,之前在网上搜索了很多方法,但大多都有重复或方法不可行,这里记录一下实现的具体过程。

使用流程

在使用mybatis进行接收的时候,由于jdbcType中不存在JSON字段,所以使用jdbcType中的OTHER类型,同时使用typeHandler对数据进行自行转换,相关配置实现大体如下:

<resultMap type="com.test.testone.use.entity.DmpRuleSetsEntity" id="UserAppsMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="data" column="data" jdbcType="OTHER" typeHandler="com.test.testone.use.util.ObjectJsonHandler"/>
    </resultMap>

在xml中加入handler的相关配置,进行实现,这里放入一个我自己使用的Handler以供大家参考。

@MappedTypes(JSONObject.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ObjectJsonHandler extends BaseTypeHandler<JSONObject>{
    
    

    //设置非空参数
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType) throws SQLException {
    
    
        ps.setString(i, String.valueOf(parameter.toJSONString()));
    }
    //根据列名,获取可以为空的结果
    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
    
    
        String sqlJson = rs.getString(columnName);
        if (null != sqlJson){
    
    
            return JSONObject.parseObject(sqlJson);
        }
        return null;
    }
    //根据列索引,获取可以为空的结果
    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    
    
        String sqlJson = rs.getString(columnIndex);
        if (null != sqlJson){
    
    
            return JSONObject.parseObject(sqlJson);
        }
        return null;
    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    
    
        String sqlJson = cs.getString(columnIndex);
        if (null != sqlJson){
    
    
            return JSONObject.parseObject(sqlJson);
        }
        return null;
    }

在配置完如上代码后,许多同学在使用的过程中发现,在本地测试没问题的情况下,换测试环境可能会出现如下错误:
could not be found for the javaType (com.alibaba.fastjson.JSONObject) : jdbcType (null) combination.
这个错误说jdbcType没有进行指明,需要指明jdbcType。但是在上面我们明明对data的类型进行了设置。

解决方案

这是由于在设置jdbcType为OTHER属性后,代码仍需要对具体的sql语句中涉及到的相关字段进行设置,比如:

update tablename
        set name = #{
    
    name},
            data = #{
    
    data,jdbcType=OTHER,typeHandler=com.test.testone.use.util.ObjectJsonHandler}
        where id = #{
    
    id}

通过这样的设置,我们就可以在代码中使用mybatis对数据库中的JSON字段进行操作

猜你喜欢

转载自blog.csdn.net/qq_43881656/article/details/126871295