mybatis 字段 default null 插入 "" 报错 MySQLSyntaxErrorException

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mingyundezuoan/article/details/82939254

mybatis 字段 default null 插入 “” 报错 MySQLSyntaxErrorException


异常描述

  • 单元测试过程中为对象赋值,其中一个字段
`description` varchar(50) DEFAULT NULL COMMENT '标签描述'
// 此处建表语句不规范,应该为 not null default ""
  • 测试时没有赋值,HTTP 接口传参 description=
  • 方法内自动将 description 赋值为 “”
  • DEBUG 跟踪对象中的 description 也为 “”
  • 插入数据时失败,打印SQL如下
[10-04 17:07:08,503] DEBUG [7197304-48][] c.t.a.m.H.insertSelective[145] - ==>  Preparing: insert into activity_tag ( creator, gmt_create, gmt_modified, is_deleted, tag, tag_name, tag_type, description ) values ( ?, ?, ?, ?, ?, ?, ? ? ) 
[10-04 17:07:08,541] DEBUG [7197304-48][] c.t.a.m.H.insertSelective[145] - ==> Parameters: 1(Integer), 2018-10-04 17:07:04.362(Timestamp), 2018-10-04 17:07:04.362(Timestamp), N(String), 1(String), 2(String), 1(Integer), (String)

  • 此时的 description 为空

SQL: insert into db_hd_activity_tag ( creator, gmt_create, gmt_modified, is_deleted, tag, tag_name, tag_type, description ) values ( ?, ?, ?, ?, ?, ?, ? ? )
Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘’’ )’ at line 47
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘’’ )’ at line 47

  • 语法错误
  • 本地运行insert|语句
INSERT into db_hd_activity_tag(creator,modifier,gmt_create,gmt_modified,is_deleted,tag,tag_name,tag_type,description)
values (1,1,NOW(),NOW(),"N","1","2",0,'') ;
  • 运行结果正常
  • 而且从日志输出来看,是MyBatis参数传入时做了过滤

异常反思

  • SQL建表语句,所有字段一律设置为 not null default 赋默认值
  • default null ,如果为空时,则不为该字段赋值,可避免上述异常

最终定位

  • 不是语法错误,也不是MyBatis过滤空字符串,是代码编写过程中,有同事在添加新字段时将字段顺序更改了,在修改 insertSelective mapper.xml 文件时,漏写了一个逗号,在 description 字段前,所以一旦description 赋值就会报错
  • 其实SQL错误信息已经很明显了

insert into db_hd_activity_tag ( creator, gmt_create, gmt_modified, is_deleted, tag, tag_name, tag_type, description ) values ( ?, ?, ?, ?, ?, ?, ? ? )

  • 最后两个赋值语句的问号之间没有逗号分隔

问题反思

  • 往往将简单的问题复杂化,其实问题本身很简单
  • 遇到问题冷静分析,一处一处排查

猜你喜欢

转载自blog.csdn.net/mingyundezuoan/article/details/82939254