PGSQL json 字段 插入失败----------- java + mybatis+ PgSQL

      针对最近遇到的一个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>

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值