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' || '%'
我記得項目初始時并沒有這種錯誤,能正常運行,可能是某些組件升級過,導致接口報錯了。