自定義 mybatis 的 TypeHandler 處理 PostgreSQL 中 json 類型字段 原

1.定義一個 JsonTypeHandler 進行處理

package com.codingos.springboot.util;

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;

import net.sf.json.util.JSONUtils;

@MappedTypes({Object.class})
public class JsonTypeHandler extends BaseTypeHandler<Object> {
    
    private static final PGobject pgObject = new PGobject();

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

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

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

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object object, JdbcType jdbcType) throws SQLException {
        pgObject.setType("json");
        pgObject.setValue(JSONUtils.valueToString(object));
        preparedStatement.setObject(i, pgObject);
    }
}

2. 在對應的相關 mapper.xml 文件中配置

<resultMap id="BaseResultMap" type="com.test.entity.EventLog">
	<id column="uuid" jdbcType="VARCHAR" property="uuid"/>
	<result column="payload" jdbcType="OTHER" property="payload" typeHandler="com.codingos.springboot.util.JsonTypeHandler"/>
</resultMap>
<insert id="insert" parameterType="com.test.entity.EventLog">
	insert into "test".event_log (uuid,payload)
	values (#{uuid,jdbcType=VARCHAR},#{payload,jdbcType=OTHER,typeHandler=com.codingos.springboot.util.JsonTypeHandler})
</insert>

在 java 代碼裏保存方法中直接傳入個 JSONObject 就可以了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章