1.实体类中字段类型
import com.alibaba.fastjson.JSONObject;@Data
public class TestDto {private String name;//对应数据库的JSON字段private JSONObject page_detail;}
2.自定义实现typeHandler
package base.utils;import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.*;import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;@MappedTypes(JSONObject.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class JsonTypeHandler extends BaseTypeHandler<JSONObject>{/*** 设置非空参数* @param ps* @param i* @param parameter* @param jdbcType* @throws SQLException*/@Overridepublic 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*/@Overridepublic 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*/@Overridepublic JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {String sqlJson = rs.getString(columnIndex);if (null != sqlJson) {return JSONObject.parseObject(sqlJson);}return null;}/**** @param cs* @param columnIndex* @return* @throws SQLException*/@Overridepublic JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {String sqlJson = cs.getNString(columnIndex);if (null != sqlJson) {return JSONObject.parseObject(sqlJson);}return null;}}
3.SQL文件
<insert id="addTest">insert into test (name,page_detail)values (#{name},#{page_detail})
</insert>
4.修改配置文件
4.1 mybatis-spring-boot-starter
由于mybatis-spring-boot-starter可无需Mybatis配置文件,可直接在项目配置文件application.properties中进行配置
#指定类型处理器的所在包的路径
mybatis.type-handlers-package=base.utils
4.1 mybatis-spring
mybatis-spring则在mybatis-config.xml中增加typeHandler
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings>//略...</settings><typeAliases>//略...</typeAliases><typeHandlers><typeHandler handler="base.utils.JsonTypeHandler"/></typeHandlers>
</configuration>
5.JDBC URL 增加配置
#jdbc增加配置stringtype=unspecified
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/test?stringtype=unspecified