解决在springboot+mybatis+postgresql时,数据库字段类型为json时,如何与mybatis进行映射
作者:互联网
pg 数据库中 某字段类型为json
Java实体中对应类型是 jsonObject
private JSONObject info;
在mybatis的xml中,常规无法直接进行映射,需要自己写一个TypeHandler,自定义一个JSONTypeHandlerPg类
具体代码:
package com.geovis.common.config;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;
@MappedTypes(Object.class)
public class JSONTypeHandlerPg extends BaseTypeHandler<Object> {
private static final PGobject jsonObject = new PGobject();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
jsonObject.setType("json");
jsonObject.setValue(parameter.toString());
ps.setObject(i, jsonObject);
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getString(columnIndex);
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getString(columnIndex);
}
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getString(columnName);
}
}
xml文件代码:
<resultMap id="BaseResultMap" type="com.geovis.domain.DataObject" >
<id column="id" property="id" />
<result column="info" property="info" javaType="Object" typeHandler="com.geovis.common.config.JSONTypeHandlerPg" />
<result column="uploadtime" property="uploadtime" jdbcType="TIMESTAMP" />
</resultMap>
插入数据时可以这么使用:
<insert id="insert" parameterType="com.geovis.domain.DataObject" >
insert into data_object(info,uploadtime)
values (#{info,javaType=Object,jdbcType=OTHER,typeHandler=com.geovis.common.config.JSONTypeHandlerPg},#{uploadtime,jdbcType=TIMESTAMP}
) returning id
</insert>
————————————————
版权声明:本文为CSDN博主「二十同学」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_18298439/article/details/80499703
标签:postgresql,springboot,rs,jsonObject,Object,SQLException,mybatis,import,public 来源: https://www.cnblogs.com/telwanggs/p/16502789.html