mybatis中typeHandler自定義實現json的讀寫


mybatis中typeHandler自定義實現typeHandler與數據庫映射JSON讀取

參考文檔

JSON 插件對比

如何自定義 typeHandler 實現json從數據庫中讀取

環境: postgreSql(DB) + springMVC + fastjson(阿里巴巴)
將 postgreSql 中json 格式的數據與 mybais轉化

步驟

1.繼承BaseTypeHandler類
該類中有四個方法

    public class JSONHandler extends BaseTypeHandler {
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
            
        }

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

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

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

重寫這四個方法,然后接着配置文件 spring-mybatis.xml (數據源配置的文件)

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 數據源配置 -->
    <property name="dataSource" ref="dataSource" />
    <!-- 自動掃描mapping.xml文件 -->
    <property name="mapperLocations" value="classpath:mapper/*/*.xml"></property>
    <!-- 加入自定義typeHandler -->
    <property name="typeHandlers">
    <!-- 示例加入多個 typeHandler -->
        <list>
            <bean class="com.xingshu.utils.typehandler.JSONArrayHandler"></bean>
            <bean class="com.xingshu.utils.typehandler.JSONObjectHandler"></bean>
        </list>
    </property>
</bean>

然后直接可以引用,經實驗,屬性名后面 typeHandler 可以直接去掉, Mybatis 會自動映射,mybatis對jdbctype 和 typeHandler 會有一個優先級的匹配,如果實現類只有一個,可以省略不寫

 <insert id="insert" parameterType="com.xingshu.bean.business.UFriendsRelation">
    insert into "UFriendsRelation" ("UHashId","UFriends","UGroupIds","UFCreateTime")
    values (
        #{UHashId},
        <if test="UFriends==null">null, </if>
        <if test="UFriends!=null">(#{UFriends,typeHandler=com.xingshu.utils.typehandler.JSONArrayHandler})::json,</if>
        <if test="UGroupIds==null">null, </if>
        <if test="UGroupIds!=null">(#{UGroupIds,typeHandler=com.xingshu.utils.typehandler.JSONObjectHandler})::json,</if>
        now()
    )
  </insert>

不寫 typehandler

 <insert id="insert" parameterType="com.xingshu.bean.business.UFriendsRelation">
    insert into "UFriendsRelation" ("UHashId","UFriends","UGroupIds","UFCreateTime")
    values (
        #{UHashId},
        <if test="UFriends==null">null, </if>
        <if test="UFriends!=null">(#{UFriends})::json,</if>
        <if test="UGroupIds==null">null, </if>
        <if test="UGroupIds!=null">(#{UGroupIds})::json,</if>
        now()
    )
  </insert>

java 類示例 JSONArrayHandler

package com.xingshu.utils.typehandler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

public class JSONArrayHandler extends BaseTypeHandler<JSONArray> {

    public JSONArray delResult(String jsonSource) throws SQLException {
        if(jsonSource != null){
            JSONArray jsonArray;
            try{
                jsonArray = JSONArray.parseArray(jsonSource);
            }catch (JSONException ex){
                throw new SQLException("There is an error converting JSONArray to json format for the content:" + jsonSource);
            }
            return jsonArray;
        }
        return null;
    }
    
    @Override
    public void setNonNullParameter(PreparedStatement ps, 
                                    int i,
                                    JSONArray parameter, //需要轉換的類型,JSON類型
                                    JdbcType jdbcType) throws SQLException {
        ps.setString(i,parameter.toJSONString());
    }

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

    @Override
    public JSONArray getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return delResult(rs.getString(columnIndex));
    }
    
    @Override
    public JSONArray getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return delResult(cs.getString(columnIndex));
    }    
    
}

java 類示例 JSONObjectHandler

package com.xingshu.utils.typehandler;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

public class JSONObjectHandler extends BaseTypeHandler<JSONObject> {

    public JSONObject delResult(String jsonSource) throws SQLException {
        if(jsonSource != null){
            JSONObject jsonObject;
            try{
                jsonObject = JSONObject.parseObject(jsonSource);
            }catch (JSONException ex){
                throw new SQLException("There is an error converting JSONObject to json format for the content:" + jsonSource);
            }
            return jsonObject;
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps,
                                    int i,
                                    JSONObject parameter, //需要轉換的類型,JSON類型
                                    JdbcType jdbcType) throws SQLException {
        ps.setString(i,parameter.toJSONString());
    }

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

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

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

}


免責聲明!

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



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