在mysql的使用过程中,我们经常会将一些json串存入mysql当中,如下json串
{
"params":[
{
"name":"zl",
"age":18,
"createTime":"2020-06-19 09:28:38",
"modifyTime":"2020-06-19 09:29:07"
}
],
"paramsTypes":[
"com.zl.platform.student"
]
}
对于这种数据在mybatis的存取过程需要一些特殊的处理,我们可以通过继承mybatis的org.apache.ibatis.type.BaseTypeHandler来实现。
首先我们需要完成一个工具类
import com.alibaba.fastjson.JSON;
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;
/**
* @Author: zl
*/
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
private Class<T> type;
public JsonTypeHandler(Class<T> type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
}
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter,
JdbcType jdbcType) throws SQLException {
ps.setString(i, JSON.toJSONString(parameter));
}
@Override
public T getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return JSON.parseObject(rs.getString(columnName), type);
}
@Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return JSON.parseObject(rs.getString(columnIndex), type);
}
@Override
public T getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return JSON.parseObject(cs.getString(columnIndex), type);
}
}
然后在mybatis中对需要使用json格式的字段引用这个方法
<resultMap id="BaseResultMap" type="com.zl.platform.entity.demo.DubboControllerInfo">
<id column="id" property="id" />
<result column="department" property="department" />
<result column="case_name" property="caseName"/>
<result column="author" property="author" />
<result column="service_name" property="serviceName" />
<result column="method_name" property="methodName" />
<result column="dubbo_params" property="dubboParams" typeHandler="com.zl.platform.utils.JsonTypeHandler"/>
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
</resultMap>
<insert id="insertDubboInfo" parameterType="com.zl.platform.entity.demo.DubboControllerInfo">
insert into dubbo_controller_info (department, author, service_name,
method_name, dubbo_params,create_time, update_time)
VALUES (#{department},#{author},#{serviceName},#{methodName},#{dubboParams,typeHandler=com.zl.platform.utils.JsonTypeHandler},
#{createTime},#{updateTime})
</insert>
<select id="selectAll" resultMap="BaseResultMap">
select * from dubbo_controller_info
</select>
这样就能使用Mybatis从mysql中取json字符串了