使用mybatis中的自定義TypeHandler處理PostgreSQL中的Json類型字段


業務擴展字段在PostgreSQL數據庫中經常會使用json格式的數據來存儲,然而mybatis默認是沒有實現json類型字段對應的TypeHandler,所以一般我們需要自定義mybatis的TypeHandler。

如下是mybatis中json類型字段對應的TypeHandler的一個簡單實現:

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

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


@MappedTypes({Object.class})
public class JsonTypeHandler extends BaseTypeHandler<Object> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws
            SQLException {
     PGobject jsonObject = new PGobject();  jsonObject.setType(
"json"); jsonObject.setValue(JsonUtil.toJsonString(o)); preparedStatement.setObject(i, jsonObject); } @Override public Object getNullableResult(ResultSet resultSet, String s) throws SQLException { return JsonUtil.fromJson(resultSet.getString(s), Object.class); } @Override public Object getNullableResult(ResultSet resultSet, int i) throws SQLException { return JsonUtil.fromJson(resultSet.getString(i), Object.class); } @Override public Object getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return JsonUtil.fromJson(callableStatement.getString(i), Object.class); } }

除了編寫TypeHandler外,還需要在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.test.dao.typehandler.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.test.dao.typehandler.JsonTypeHandler})
    </insert>

使用時,獲取到該Object對象后,可先轉成json字符串,再轉成對應的對象,如下:

        EventLogPayload eventLogPayload = JsonUtil.parser(JsonUtil.toJson(eventLog.getPayload()), EventLogPayload.class);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM