MyBatis-Plus的自带分页方法生成的SQL失败:The error occurred while setting parameters
1、error描述
数据库是postgres,Java使用mybatis-plus的分页功能,生成的分页SQL不能正常运行。
"msg": "nested exception is org.apache.ibatis.exceptions.PersistenceException: Error querying database.
Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Error: Method queryTotal execution error of sql : SELECT COUNT(1) FROM mfile file WHERE (1 = 1) AND file.file_name LIKE CONCAT('%', ?, '%') The error may exist in URL [jar:file:/**/mapper/**Mapper.xml]The error may involve defaultParameterMap<br/>The error occurred while setting parameters<br/>Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException:
Error: Method queryTotal execution error of sql : SELECT COUNT(1) FROM mfile file WHERE (1 = 1) AND file.file_name LIKE CONCAT('%', ?, '%') <br/>
2、Java代码
public IPage<MFileVO> queryByPage(MFileVO mFile) throws SQLException, ClassNotFoundException {IPage<MFileVO> mFileEntityIPage = baseMapper.queryByPage(mFile.mkPage(), mFile);...}
3、mapper的SQL
select file.*,version.version_number as versionNumberfrom file fileleft join file_version version on version.id=file.version_idwhere (1=1)<if test="entity.dataGuid != null and entity.dataGuid != ''">AND file.data_parent_ids like CONCAT('%', #{entity.dataGuid}::VARCHAR, '%')</if><if test="entity.fileName != null and entity.fileName != ''">AND file.file_name like CONCAT('%', #{entity.fileName}, '%')</if>
4、原因
- CONCAT 在 PostgreSQL 中的行为
PostgreSQL 不支持 CONCAT() 函数,应使用 || 进行字符串拼接。
示例错误写法:
LIKE CONCAT('%', #{entity.fileName}, '%')
正确写法(推荐):
LIKE '%' || #{entity.fileName} || '%'
5、测试
修改前,MayBatis-Plus自动生成的分页count语句能在Navicat和pgadmin4中正常执行,运行代码时报错
SELECTCOUNT(1)
FROMmfile file
WHERE(1 = 1) AND file.file_name LIKE CONCAT('%', 'test', '%');
修改后运行代码也不报错了,自动生成的分页count语句如下
SELECTCOUNT(1)
FROMmfile file
WHERE(1 = 1) AND file.file_name LIKE '%' || 'test' || '%'
我记得项目初始时并没有这种错误,能正常运行,可能是某些组件升级过,导致接口报错了。