Resolving PageHelper Malfunction When Using MyBatis and MyBatis-Plus Together
Issue Origin
Recently, I took over a project that uses MyBatis and MyBatis-Plus for database operations. We needed to add new functionality to this system.
During development, everything went smoothly, and I quickly completed my part of the module. Then, I started integrating with the front end. However, during testing, an issue was found: the backend did not return pagination information, and our feature required it. I immediately began troubleshooting and confirmed that no pagination data was being returned.
The problem occurred during the query process, and I had already set the pagination parameters as follows:
PageHelper.startPage(pageReq.getPageNum(), pageReq.getPageSize());
I also added the following configuration in the configuration file:
pagehelper.helper-dialect=mysql pagehelper.reasonable=true pagehelper.support-methods-arguments=true pagehelper.params=count=countSql pagehelper.rowBoundsWithCount=true pagehelper.offsetAsPageNum=true
It should have worked correctly, but it didn't.
Problem Analysis
After testing, it was confirmed that no pagination data was returned. I used breakpoints to check whether the Service layer returned any pagination data, and the result was negative.
The issue was during the query. I had already set the pagination parameters and configured the settings, yet the problem persisted.
Solutionn
I searched online and asked colleagues for solutions. I tried various approaches without success.
Attempt 1: Add the PageHelper starter dependency in the pom.xml file. It did not resolve the issue.
Attempt 2: Add the following dependency:
The test results showed no improvement.
Attempt 3: Create a class to initialize the PageInterceptor class. This attempt succeeded, and the pagination data was returned correctly. The code is as follows:
import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.spring.boot.starter.ConfigurationCustomizer; import com.github.pagehelper.PageInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration public clas MyBatisPlusConfig {
/*
* Pagination plugin, automatically identifies the database type
* For multi-tenant support, refer to the official documentation
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
PageInterceptor pageInterceptor(){
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect", "mysql");
pageInterceptor.setProperties(properties);
return pageInterceptor;
}
}
After multiple attempts, the issue was finally resolved, although the exact cause remains unclear. My assumption is that when using MyBatis-Plus, the PageInterceptor class is no longer generated automatically, which is why manual creation is necessary.