首先介绍一下MyBatis PLUS原生分页插件
https://blog.csdn.net/qq_31275085/article/details/86716909
上面链接写的非常清楚,有兴趣的可以看看。接下来我们主要看看坑点。
坑点:
1、该插件使用后,每次查询的时候都会默认进行count一次,其实这导致你的分页并没有什么意义,还是查询全部。
如果查询单表的时候并没有什么问题,但是像我一样,需求复杂,需要多个join的时候就有问题了。本来利用分页其原因有一部分就是减少每次的查询量,但是,使用分页插件后,每次都会进行一次count查询,这里的count查询并没zh有进行任何优化,而是在你的sql的基础上直接count。
Page<StaffInfo> p = new Page<>(page, pageSize);
public Page(long current, long size, boolean isSearchCount) { this(current, size, 0L, isSearchCount); }
public Page(long current, long size, long total, boolean isSearchCount) { this.records = Collections.emptyList(); this.total = 0L; this.size = 10L; this.current = 1L; this.optimizeCountSql = true; this.isSearchCount = true; if (current > 1L) { this.current = current; } this.size = size; this.total = total; this.isSearchCount = isSearchCount; }
代码中所示:isSearchCount这个字段实际上默认是true,表示要进行count统计。我们如果不注意,而且sql又比较复杂,就容易掉入这个坑里面。
所以我们在使用的时候如下:
Page<StaffInfo> p = new Page<>(page, pageSize,false);
这样就不会触发count,但是好的count的方法现在暂时没找到替代的方法。
2、优化sql;
当你的sql中有大量的join的时候,同时又使用分页插件的话,最好将数据量大,而且比较复杂的join对象进行拆分,在后端根据已经查好的数据的条件进行单表查询,这样 会带来比较好的sql的性能的提升。