How springboot integrates mybatis paging interceptor
Introduction
When I was developing today, I wanted to optimize the code I wrote, because I didn’t want to do it on the development server, and I was afraid that it would cause a lot of problems in GIT when it comes to the production server, and then separate it. Turning to my wheel (tool) project, after the final run, I found that it was stuck for at least 10 seconds when getting the List. I was shocked. My normal version usually takes about 800ms (don’t look at it for a long time, because the amount of data is huge, and It's normal.), the premise is that I also know that it is very slow. When it really needs optimization, I will release my optimized plus version and go back to 10 seconds. When I first received this app project, when I used PageHelper .startPage(page, num); (paging), the page has been divided before the data encapsulation (PageInfo) is found. Now I have found this problem when I switch to the wheel. It does not help me splice limit into sql. Later, I got all of them and then PageInfo paging. The huge amount of data caused it to be very stuck. Finally...
10 seconds:
Normal:
springboot integrates mybatis paging interceptor
Paging interception is actually to get the sql and then splice the sql into limit
pom.xml
<!-- 引入分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency>
yml
spring: application: name: spring-cloud-dynamic datasource: #类型 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/f2f?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: initial-size: 2 max-idle: 10 min-idle: 1 max-wait: 60000 max-active: 20 #最大空闲连接数 #多久进行一次检测,检测需要关闭的空闲连接 time-between-eviction-tuns-millis: 60000
MybatisConfig
/** * @author lanys * @Description: * @date 23/7/2021 下午8:38 */ @Configuration @EnableTransactionManagement @PropertySource(value = "classpath:application.yml", ignoreResourceNotFound = true) public class MybatisConfig implements TransactionManagementConfigurer { @Value("${mybatis.mapper-locations}") private String mapper; @Value("${mybatis.type-aliases-package}") private String aliases; @Autowired private DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); // 设置数据源 bean.setDataSource(dataSource); // 设置xml bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper)); // 设置别名 bean.setTypeAliasesPackage(aliases); // 添加分页插件 bean.setPlugins(new Interceptor[]{pageInterceptor()}); bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true); return bean.getObject(); } /** * 分页拦截器 * @return */ private PageInterceptor pageInterceptor() { PageInterceptor pageInterceptor = new PageInterceptor(); // 详见 com.github.pagehelper.page.PageParams Properties p = new Properties(); // RowBounds是否进行count查询 - 默认不查询 p.setProperty("rowBoundsWithCount", "true"); // 当设置为true的时候,如果page size设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果 p.setProperty("pageSizeZero", "true"); // 分页合理化 p.setProperty("reasonable", "false"); // 是否支持接口参数来传递分页参数,默认false p.setProperty("supportMethodsArguments", "true"); // 设置数据库方言 , 也可以不设置,会动态获取 p.setProperty("helperDialect", "mysql"); pageInterceptor.setProperties(p); return pageInterceptor; } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } }
Test
My own code
/** * 关注列表 * @param userId * @param page * @param size * @return */ @Override public List<DynamicInfo> focusList(Long userId, Integer page, Integer size) { PageHelper.startPage(page, size); List<DynamicInfo> listByUserId = new ArrayList<>(); try { //获取自己关注列表 listByUserId = this.dynamicReleaseMapper.getListFocusId(userId); if (listByUserId == null || listByUserId.size() == 0){ return listByUserId; } //List<DynamicInfo> listByUserId = this.dynamicReleaseMapper.getListFocusId(userId).stream().filter(x->(x.getIsPicture()!=2 && x.getIsVideo() !=2)||(x.getIsPicture()==2 && x.getIsVideo() !=2)||(x.getIsPicture()!=2 && x.getIsVideo() ==2)).collect(Collectors.toList()); publicGetDynamicInfo(userId,listByUserId); //} log.info("-------获取关注列表-------"); return listByUserId; } catch (Exception e) { log.error("获取关注列表异常",e); } return listByUserId; }
If you want to paginate, add PageHelper.startPage(page, size);, Otherwise, paging will not be done by default. You can also add limit yourself.
Result (a part of the sql statement is very long):
GROUP BY id ORDER BY create_time desc LIMIT ?
The above is the detailed content of How springboot integrates mybatis paging interceptor. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

iBatis vs. MyBatis: Which should you choose? Introduction: With the rapid development of the Java language, many persistence frameworks have emerged. iBatis and MyBatis are two popular persistence frameworks, both of which provide a simple and efficient data access solution. This article will introduce the features and advantages of iBatis and MyBatis, and give some specific code examples to help you choose the appropriate framework. Introduction to iBatis: iBatis is an open source persistence framework

Several ways to implement batch deletion statements in MyBatis require specific code examples. In recent years, due to the increasing amount of data, batch operations have become an important part of database operations. In actual development, we often need to delete records in the database in batches. This article will focus on several ways to implement batch delete statements in MyBatis and provide corresponding code examples. Use the foreach tag to implement batch deletion. MyBatis provides the foreach tag, which can easily traverse a set.

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

Detailed explanation of how to use MyBatis batch delete statements requires specific code examples. Introduction: MyBatis is an excellent persistence layer framework that provides rich SQL operation functions. In actual project development, we often encounter situations where data needs to be deleted in batches. This article will introduce in detail how to use MyBatis batch delete statements, and attach specific code examples. Usage scenario: When deleting a large amount of data in the database, it is inefficient to execute the delete statements one by one. At this point, you can use the batch deletion function of MyBatis

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes
