针对最近遇到的一个sql插入问题:表中有一个字段为json,jdbcType=other ,但是无论用对象还是string字符要么报字段为空,要么说输入的是字符串无法装换成json字段。参考了网上很多博客,终于找到一种方法,自己写一个继承org.apache.ibatis.type.BaseTypeHandler类型处理器类,并在mapper映射的xml文件中指定类型,具体步骤如下:
-
修改自动生成的实体类的字段类型 Object -> com.alibaba.fastjson.JSONObject
@Column(name = "youyou")
private List<JSONObject> youyou;
-
写一个JSONTYPEHandler类
-
import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedTypes; import org.postgresql.util.PGobject; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @MappedTypes(Object.class) public class JSONTypeHandler 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); } }
- 在**mapper.xml文件中指定对应的类型
-
<result column="you_you" javaType="Object" property="youyou" jdbcType="OTHER" typeHandler="**.util.JSONTypeHandlerPg" />
<insert id="insertYouYou" parameterType="**.YouYou" > insert into t_table ( you_you) values ( #{youYou.youyou,javaType=Object,jdbcType=OTHER,typeHandler=**.JSONTypeHandlerPg} ); </insert>
<update id="updateYouYou"> update t_table set you_you= #{youYou.youyou,javaType=Object,jdbcType=OTHER,typeHandler=**.JSONTypeHandlerPg}, mtime = #{youYou.mtime} where you_id = #{youYou.youId}; </update>