一般情况下,MyBatis-Plus拼装的列表查询语句是类似下面这样的:
SELECT id,name,gender,age,address,telephone,is_show FROM staff
但这次实测时,却在控制台输出了这样让人大跌眼镜的语句:
2021-01-07 10:57:34.822 DEBUG 36624 --- [nio-7000-exec-1] c.e.b.***.dao.xxxDao.selectPage : ==> Preparing:
SELECT id,name,gender,age,address,telephone,is_show FROM staff WHERE is_show=1
另外,本来好好的UPDATE staff SET address=? WHERE id=?
或UPDATE staff SET is_show=? WHERE id=?
之类的语句,却一不留神被变成了下面的画风:
UPDATE staff SET address=? WHERE id=? AND is_show=1
UPDATE staff WHERE id=? AND is_show=1 -- (这没有SET子句的UPDATE是什么鬼?——编者问)
经过反复多次实验,发现问题的症结所在,就是在application.yml中配置了逻辑删除字段。如下所示:
mybatis-plus:
mapper-locations: classpath:/mapper/**/*.xml
global-config:
db-config:
id-type: auto
logic-delete-field: isShow # 全局逻辑删除的实体字段名
logic-delete-value: 0 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 1 # 逻辑未删除值(默认为 0)
------------------------------------------------始料未及的分割线---------------------------------------------------
如果需要设置逻辑删除字段,又不想出现上面诡异的SQL语句,可以参考我前面刚写的《SpringCloud整合MyBatis-Plus逻辑删除配置错误时可能导致的严重后果》中的“方案二”。
总之,如果逻辑删除字段设置不当,不仅有误删数据的可能,还可能会看到页面及后端出现的语意不清的异常,如:
1、前端控制台异常:
POST http://localhost:88/api/company/***/update 500 (Internal Server Error)
Uncaught (in promise) Error: Request failed with status code 500
at createError (createError.js?16d0:16)
at settle (settle.js?db52:18)
at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)
2、后端控制台异常:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed;
nested exception is org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: 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 'WHERE id=7 AND is_show=1' at line 1
### The error may exist in com/xxx/xxxx/company/dao/***Dao.java (best guess)
### The error may involve com.xxx.xxxx.company.dao.***Dao.updateById-Inline
### The error occurred while setting parameters
### SQL: UPDATE staff WHERE id=? AND is_show=1
### Cause: java.sql.SQLSyntaxErrorException: 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 'WHERE id=7 AND is_show=1' at line 1;bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: 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 'WHERE id=7 AND is_show=1' at line 1] with root cause
由于上面的问题原因比较隐蔽,影响巨大,所以,在MyBatis-Plus中使用逻辑删除字段时,需要三思而行!