一. 问题引入
报错内容:
Error querying database. Cause: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Invalid JSON text in argument 1 to function json_extract: “The document is empty.” at position 0. ### The error may exist in class path resource [mapper/equipment/EquDevModelMapper.xml] ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: SELECT GROUP_CONCAT(styles_json) styles_json FROM (SELECT DISTINCT json_extract(styles_json,’$[*]’) styles_json FROM devModel_Model ) dm ### Cause: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Invalid JSON text in argument 1 to function json_extract: “The document is empty.” at position 0. ; Data truncation: Invalid JSON text in argument 1 to function json_extract: “The document is empty.” at position 0.; nested exception is com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Invalid JSON text in argument 1 to function json_extract: “The document is empty.” at position 0.
出错问题点在sql语句:
SELECT GROUP_CONCAT(styles_json) styles_json FROM (SELECT DISTINCT json_extract(styles_json,’$[*]’) styles_json FROM devModel_Model ) dm
二. 问题分析
直接进sql语句查询,很明显是说里面有个空值不符合规范。
因为本身就是用json函数查询,本身传入的值要符合规范,空字符串本身就是不符合json规范的,所以出错。
报错内容:
SELECT GROUP_CONCAT(styles_json) styles_json FROM (SELECT DISTINCT json_extract(styles_json,’$[*]’) styles_json FROM devModel_Model ) dm
Invalid JSON text in argument 1 to function json_extract: “The document is empty.” at position 0.
时间: 0.003s
三. 解决方案
- 如果本身有字符串回传进去,直接进行判断,防止sql报错
解决方案:sql的if函数
if(styles_json = ‘’,null,styles_json)
查询的时候对本身不符合规范的空字符串进行筛选。
如果是是空设置为null,防止报错。
新的sql就没问题了。
SELECT GROUP_CONCAT(styles_json) styles_json
FROM (SELECT DISTINCT json_extract(if(styles_json = '',null,styles_json),'$[*]') styles_json FROM devModel_Model ) dm
主要功能是对查询出来的一列数据放在一行中并进行初步去重。
- 对前端回传的字符串进行判断
2.1 查询的时候如果是空字串和null不进行查询
2.2 新增如果是空字串和null就不新增
2.3 更新时候是空字串就不更改
可以设置为null
四. 总结
如果在数据库中删除留下空字符就会报错,因为本身json函数无法操作非json的数据,如果用的varchar存的,就会出现这个问题,如果是用json格式存的数据,会排除空字符串这种非空数据。