1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package com.nuliji.tools.mybatis.handler;
- import com.alibaba.fastjson.JSONObject;
- import org.apache.ibatis.type.BaseTypeHandler;
- import org.apache.ibatis.type.JdbcType;
- import org.apache.ibatis.type.MappedJdbcTypes;
- import org.apache.ibatis.type.MappedTypes;
- import java.sql.*;
- /**
- * @description 用以mysql中json格式的字段,进行转换的自定义转换器,转换为实体类的JSONObject属性
- */
- @MappedTypes(JSONObject.class)
- @MappedJdbcTypes(value = {JdbcType.LONGVARCHAR, JdbcType.VARCHAR}, includeNullJdbcType = true)
- public class JsonObjectHandler extends BaseTypeHandler<JSONObject> {
- public JsonObjectHandler(){
- }
- /**
- * 设置非空参数
- * @param ps
- * @param i
- * @param parameter
- * @param jdbcType
- * @throws SQLException
- */
- @Override
- public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType) throws SQLException {
- ps.setString(i, String.valueOf(parameter.toJSONString()));
- }
- /**
- * 根据列名,获取可以为空的结果
- * @param rs
- * @param columnName
- * @return
- * @throws SQLException
- */
- @Override
- public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
- String sqlJson = rs.getString(columnName);
- if (null != sqlJson){
- return JSONObject.parseObject(sqlJson);
- }
- return null;
- }
- /**
- * 根据列索引,获取可以为空的结果
- * @param rs
- * @param columnIndex
- * @return
- * @throws SQLException
- */
- @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;
- }
- }
|