1. 程式人生 > 其它 >使用MyBatis的pageHelper進行分頁踩坑記錄(java.sql.SQLSyntaxErrorException)

使用MyBatis的pageHelper進行分頁踩坑記錄(java.sql.SQLSyntaxErrorException)

技術標籤:mybatismybatismysqljava分頁pageHelper

問題描述

環境:

mybatis 3.4.6
MySQL資料庫

描述:

在學習MyBatis分頁過程中,對MySQL資料庫分頁時出現以下SQLSyntaxErrorException異常:

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 'LIMIT 3' at line 1

該異常屬於Sql語句發生異常,提示說LIMIT 3附近出現語句格式錯誤。
java出錯部分程式碼:

public class Test5 {
    public static void main(String[] args) throws IOException {
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml")).openSession();
        
        PageHelper.
startPage(1, 3); UserDao dao = sqlSession.getMapper(UserDao.class); List<User> users1 = dao.getAll(); PageInfo<User> userPageInfo = new PageInfo<>(users1); List<User> list1 = userPageInfo.getList(); list1.forEach(user -> System.out.
println(user)); } }

getAll方法的Mapper配置:

<select id="getAll" resultType="user">
        select * from User;
</select>

解決方案

通過使用log4j列印日誌:

 2021-01-18 09:38:29,839 [main] DEBUG [com.kkb.dao.UserDao.getAll] - ==>  Preparing: select * from User; LIMIT ? 
 2021-01-18 09:38:29,840 [main] DEBUG [com.kkb.dao.UserDao.getAll] - ==> Parameters: 3(Integer)

可以發現,MyBatis分頁外掛拼接的sql語句中:“select * from User; LIMIT ?”,中間多了個分號,所以將Mapper配置檔案中的sql語句句尾處的 ;去掉即可。

將getAll方法的Mapper配置改成:

<select id="getAll" resultType="user">
        select * from User
</select>