在springboot中使用mybatis-plus
在pom文件导入
<!--引人mybatis-plus的依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--引入阿里巴巴的druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
2.在papplication.properties配置数据库信息
server.port=8088
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/activity_service?characterEncoding=UTF-8
spring.datasource.username=activity_service
spring.datasource.password=123213
3.编写mapper接口继承BaseMapper<表的实体类>
package com.activity.mapper;
import com.activity.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper extends BaseMapper<User> {
}
4.使用分页插件
先新建一个类,带上分页插件
package com.activity.common.Page;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Page {
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
在test测试文件中
package com.activity;
import com.activity.entity.Aclog;
import com.activity.mapper.AclogMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;
@SpringBootTest
class ManagementApplicationTests {
@Resource
private AclogMapper aclogMapper;
@Test
void contextLoads() {
//1.创建对象
//2.传入两个参数,
Page<Aclog> page=new Page<>(2,5);
//调用map的分页查询方法
//调用mp分页查询过程中,底层封装
//把分页所有数据封装到page对象里面
IPage<Aclog> aclogIPage = aclogMapper.selectPage(page, null);
List<Aclog> records = aclogIPage.getRecords();
for(Aclog aclog:records){
System.out.println(aclog);
}
//通过page对象获取到分页
System.out.println(page.getCurrent());//当前页
System.out.println(page.getRecords());//每夜数据list集合
System.out.println(page.getSize());//每页现实记录数
System.out.println(page.getTotal());//总记录数
System.out.println(page.getPages());//总页数
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
}