配置过程
applicationContext.xml:
<!--配置sessionFactory-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<!--数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--插件-->
<property name="plugins">
<array>
<ref bean="mybatisPlusInterceptor"/>
</array>
</property>
</bean>
<!--插件-->
<bean id="mybatisPlusInterceptor" class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
<property name="interceptors">
<list>
<ref bean="paginationInnerInterceptor"/>
</list>
</property>
</bean>
<bean id="paginationInnerInterceptor" class="com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor">
<!-- 对于单一数据库类型来说,都建议配置该值,避免每次分页都去抓取数据库类型 -->
<constructor-arg name="dbType" value="H2"/>
</bean>
config.java:
@Configuration
@MapperScan("mapper") //设置mapper接口的扫描包
public class PageConfig {
//分页插件
@Bean
public PaginationInnerInterceptor paginationInterceptor() {
return new PaginationInnerInterceptor();
}
}
测试:
@Test
public void testSelectPage() {
QueryWrapper<User> wrapper = new QueryWrapper<User>();
wrapper.gt("age", 20);
Page<User> page = new Page<>(1,1);//要查询的页码;每页数据条数
//根据条件查询数据
IPage<User> iPage = mapper.selectPage(page, wrapper);
System.out.println("数据总条数:" + iPage.getTotal());
System.out.println("总页数:" + iPage.getPages());
List<User> users = iPage.getRecords();
for (User user : users) {
System.out.println(user);
}
}