Mybatis处理PostgreSQL中jsonb的数据
出现的问题
Mybatis只能是将java中的字段与数据库的字段做映射,字段的类型需要匹配才能完成数据映射。
但是Mybatis中没有json或者jsonb的的type的。所以要操作PostgreSQL中json或者jsonb数据,需要自己写一个支持JsonbTypeHandler。
解决方式
继承BaseTypeHandler重写JsonbTypeHandler
package com.junction.util;
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 JsonbTypeHandler extends BaseTypeHandler<Object> {
//报错的话,请将pom文件的引入graphql的地方<version></version>标签注释掉
private static final PGobject jsonObject = new PGobject();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
throws SQLException {
if (ps != null) {
jsonObject.setType("jsonb");
jsonObject.setValue(parameter.toString());
ps.setObject(i, jsonObject);
}
}
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getObject(columnName);
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getObject(columnIndex);
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getObject(columnIndex);
}
}
修改mapper.xml指定typeHandler
<resultMap type="User" id="userResultMap">
<id property="id" column="id" />
<result property="active" column="active" />
<result property="sn" column="sn" />
<result property="name" column="name" />
<result property="kind" column="kind" />
<result property="gender" column="gender" />
<result property="age" column="age" />
<result property="remark" column="remark" />
<result property="data" column="data" jdbcType="OTHER"
typeHandler="com.junction.util.JsonbTypeHandler" />
</resultMap>
<select id="selectUser" parameterType="java.lang.Long"
resultMap="userResultMap">
select *
from users where id = #{id}
</select>
insert的时候可以这么写:
<insert id="insertUser" parameterType="User">
insert into users
values(#{id},#{active},#{sn},#{name},#{kind},#{gender},#{age},#{remark},#{data,jdbcType=OTHER,typeHandler=com.junction.util.JsonbTypeHandler})
</insert>