1. 程式人生 > >解決在springboot+mybatis+postgresql時,資料庫欄位型別為json時,如何與mybatis進行對映

解決在springboot+mybatis+postgresql時,資料庫欄位型別為json時,如何與mybatis進行對映

pg 資料庫中 某欄位型別為json

Java實體中對應型別是 jsonObject   

private JSONObject info;

在mybatis的xml中,常規無法直接進行對映,需要自己寫一個TypeHandler,自定義一個JSONTypeHandlerPg類

具體程式碼:

package com.geovis.common.config;

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

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

@MappedTypes(Object.class)
public class JSONTypeHandlerPg extends BaseTypeHandler<Object> {
	
    private static final PGobject jsonObject = new PGobject();
    
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        jsonObject.setType("json");
        jsonObject.setValue(parameter.toString());
        ps.setObject(i, jsonObject);
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getString(columnIndex);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getString(columnIndex);
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return rs.getString(columnName);
    }

}

xml檔案程式碼:

<resultMap id="BaseResultMap" type="com.geovis.domain.DataObject" >
    <id column="id" property="id" />
    <result column="info" property="info" javaType="Object" typeHandler="com.geovis.common.config.JSONTypeHandlerPg" />
    <result column="uploadtime" property="uploadtime" jdbcType="TIMESTAMP" />
  </resultMap>

插入資料時可以這麼使用:

<insert id="insert" parameterType="com.geovis.domain.DataObject" >
    insert into data_object(info,uploadtime)
    values (#{info,javaType=Object,jdbcType=OTHER,typeHandler=com.geovis.common.config.JSONTypeHandlerPg},#{uploadtime,jdbcType=TIMESTAMP}
      ) returning id
  </insert>