• Ibatis insert语句插入null引发的错误


    公司使用的orm框架为ibatis,其中默认的insert语句一直都是这样写的:

     1 <insert id="insert" parameterClass="activityDO" >
     2         insert into activity_expert (
     3             ......
     4             activity_id ,
     5             ......
     6             )
     7         values(
     8             ......
     9             #activityId# ,
    10             ......
    11         )
    12 </insert>

    很常规的写法对吧!

    假设其中activity_id是不可为null的,在写表结构时默认如果为null,则activity_id=99。

    总体来看,insert语句是没有问题的,如果activity_id不为null,则正常入库,如果为null,还有默认值default=99,但是实际上却并不是这样的,如果对象中的activityId为null,程序会报错。

    经查阅,上述的规则其实是不正确的,正确的规则如下:

    在insert语句中,如果显式地插入NULL值(如:insert into test values (null))到被声明了NOT NULL的列,则将会报错,不允许插入;而如果是隐式地插入NULL值(如:insert into test values ())到被声明了NOT NULL的列,列应该被设置为它的缺省值,如果它有缺省值的话,否则报错,无法插入。

    因此在ibatis中写insert语句的最佳方式如下:

     1 <sql id="common_condition">
     2     ......
     3     <isNotEmpty prepend="," property="activityId"  removeFirstPrepend="true">activity_id = #activityId# </isNotEmpty>
     4     ......
     5 </sql>
     6  
     7 <insert id="insert" parameterClass="activityExpertDO" >
     8     insert into activity set
     9     <include refid="common_condition" />
    10 </insert>

    这样做一方面可以解决上述表中某些字段不能为null,但传递参数却又有可能为null的情况,另外一方面可以复用sql语句,在insert和update的sql语句中都可以使用。

  • 相关阅读:
    个人作业——软件评测
    2020软件工程实践 作业3
    2020软件工程实践 寒假作业2
    2020软件工程实践 寒假作业1
    计网大概
    大写金额转换实现
    软件工程实践总结&个人技术博客
    个人技术博客
    软件评测
    疫情统计实现
  • 原文地址:https://www.cnblogs.com/liaochong/p/ibatis_insert.html
Copyright © 2020-2023  润新知