1. 程式人生 > >mybatis 欄位 default null 插入 "" 報錯 MySQLSyntaxErrorException

mybatis 欄位 default null 插入 "" 報錯 MySQLSyntaxErrorException

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 ( ?, ?, ?, ?, ?, ?, ? ? )

  • 最後兩個賦值語句的問號之間沒有逗號分隔

問題反思

  • 往往將簡單的問題複雜化,其實問題本身很簡單
  • 遇到問題冷靜分析,一處一處排查