springboot/mybatis传实体类参数为空,通过设置jdbcType来减少mybatis代码量

过去参数这块一直没有细究,往往是出问题后百度,解决后遗忘,下次继续百度

1.错误代码

mybatis中实现插入操作

<insert id="insertDetail" parameterType="com.user.po.Vaccine">
        insert into vaccine_question_t(empno,empname,will,status,road,location,reason,tel,create_time)
        values(#{empno},#{empname},#{will},
               #{status},#{road},#{location},
               #{reason},#{tel},sysdate)
    </insert>

swagger中这样传参数
用户要求除了第一项其他都可能为空

以上操作后会java会报错,找到cause

Cause: org.apache.ibatis.type.TypeException: Error setting null for parameter #2 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException: 无效的列类型: 1111

由错误信息可以得出,第二个参数是JdbcType OTHER类型,无法传空。

2.解决方法

  1. 利用mybatis中的条件判断
    为可以传空的参数加上if条件判断,如果参数为空,那对应的sql语句将不会出现。
<if test='empname!=null and empname!=""'>
            ,#{empname}
        </if>
  1. 设置mybatis参数jdbcType类型
    上面报错提到 JdbcType OTHER 类型不能传空,而我们不设置时默认就是这个类型。那么我们可以将需要的参数加上对应的类型。
<insert id="insertDetail" parameterType="com.foxconn.user.po.Vaccine">
        insert into vaccine_question_t(empno,empname,will,status,road,location,reason,tel,create_time)
        values(#{empno,jdbcType=VARCHAR},#{empname,jdbcType=VARCHAR},#{will,jdbcType=VARCHAR},
               #{status,jdbcType=VARCHAR},#{road,jdbcType=VARCHAR},#{location,jdbcType=VARCHAR},
               #{reason,jdbcType=VARCHAR},#{tel,jdbcType=VARCHAR},sysdate)
    </insert>

这样一来,就可以完成insert操作,操作台结果如下
在这里插入图片描述


版权声明:本文为yumekawa2020原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。