SpringBoot集成MyBatis-Plus实现分页查询

  1. 引入MyBatis-Plus依赖,下面注意指定自己的MyBatis-Plus版本。
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus.version}</version>
</dependency>
  1. 配置分页查询插件,将其配置到启动类或者配置类都可以。
@Bean
@ConditionalOnMissingBean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
    paginationInnerInterceptor.setMaxLimit(200L);// 限制每页最多显示200条记录。
    interceptor.addInnerInterceptor(paginationInnerInterceptor);
    return interceptor;
}
  1. 准备好数据库表,以及对应的实体类,并且准备好对应的mapper以及service
@TableName("t_user") // 注解设置实体类对应数据库的表名
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {

    // MyBatisPlus默认将主键 id作为主键,但是表的字段名可能不是 id,可能是 uid之类的
    // @TableId注解将该属性作为主键,如遇到表中字段名不为id且是主键是要通过 @TableId注解
    // 若实体类和表中表示主键的不是id,而是其他字段,例如uid,程序抛出异常,Field 'uid' doesn't have a default value,说明MyBatis-Plus没有将uid作为主键赋值
    // value 属性用于指定主键的字段
    // type 属性用于指定自增策略(默认雪花算法)
    // IdType.AUTO 根据数据库最大id值自增(前提是设置了该字段设置了 auto_increment)
    // IdType.ASSIGN_ID 雪花算法生成 id(默认)
    // IdType.ASSIGN_UUID 生成UUID 作为字段的 id
    // IdType.NONE 不使用任何主键生成策略,由程序自行生成主键。
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private Long id;

    //非主键 -> 通过 @TableField("name")注解将实体类的属性映射到表的对应字段
    @TableField("name")
    private String name;
    private Integer age;
    private String email;
    private SexEnum sex;

    //逻辑删除(用于数据恢复)
    @TableLogic
    private Integer isDelete;
}
@Repository
public interface UserMapper extends BaseMapper<User> {}
  1. 封装vo类返回Page对象
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.Objects;

@Data
public class PageQuery<T> {

    private final static Integer DEFAULT_PAGE_NUM = 1;
    private final static Integer DEFAULT_PAGE_SIZE = 5;
    
    private Integer pageNo = DEFAULT_PAGE_NUM;
    private Integer pageSize = DEFAULT_PAGE_SIZE;
    private String sortBy = "age";// 排序字段,默认使用 age
    private Boolean isAsc = true;// 排序方式,默认升序

    public Page<T> toMpPage(String sortBy, Boolean isAsc, Integer pageNo, Integer pageSize) {
        if (!StringUtils.isBlank(sortBy)) {
            this.sortBy = sortBy;
        }
        if (!Objects.isNull(isAsc)) {
            this.isAsc = isAsc;
        }
        if (!Objects.isNull(pageNo)) {
            this.pageNo = pageNo;
        }
        if (!Objects.isNull(pageSize)) {
            this.pageSize = pageSize;
        }
        Page<T> page = new Page<>(this.pageNo, this.pageSize);
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(this.isAsc);
        orderItem.setColumn(this.sortBy);
        page.addOrder(orderItem);
        return page;
    }
}
  1. 测试分页结果
public class TestPage {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testPage() {
        PageQuery<User> pageQuery = new PageQuery<>();
        Page<User> page = pageQuery.toMpPage("age", true, 1, 5);
        Page<User> resPage = userMapper.selectPage(page, new LambdaQueryWrapper<>());// 传入page对象以及LambdaQueryWrapper
        System.out.println(resPage.getCurrent());// 当前页码
        System.out.println(resPage.getSize());// 每页显示条数
        System.out.println(resPage.getPages());// 总页数
        System.out.println(resPage.getTotal());// 总记录数
        List<User> records = resPage.getRecords();// 符合条件的记录
        records.forEach(System.out::println);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot是一个高效的Java开发框架,它能够方便开发者集成MyBatis-Plus实现多数据源的动态切换以及支持分页查询MyBatis-Plus是一种优秀的ORM框架,它增强了MyBatis的基础功能,并支持通过注解方式进行映射。 首先,我们需要在pom.xml文件中添加MyBatis-Plus和数据库连接池的依赖。在application.yml文件中,我们需要配置多个数据源和对应的连接信息。我们可以定义一个DataSourceConfig用于获取多个数据源,然后在Mapper配置类中使用@MapperScan(basePackages = {"com.test.mapper"})来扫描Mapper接口。 要实现动态切换数据源,我们可以自定义一个注解@DataSource来标注Mapper接口或方法,然后使用AOP拦截数据源切换,实现动态切换。在实现分页查询时,我们可以使用MyBatis-Plus提供的分页插件来支持分页查询。 代码示例: 1. 在pom.xml文件中添加MyBatis-Plus和数据库连接池的依赖。 ``` <dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.4</version> </dependency> </dependencies> ``` 2. 在application.yml文件中配置多个数据源和对应的连接信息。以两个数据源为例: ``` spring: datasource: druid: db1: url: jdbc:mysql://localhost:3306/db1 username: root password: root driver-class-name: com.mysql.jdbc.Driver db2: url: jdbc:mysql://localhost:3306/db2 username: root password: root driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 指定默认数据源 primary: db1 ``` 3. 定义一个DataSourceConfig用于获取多个数据源。 ``` @Configuration public class DataSourceConfig { @Bean("db1") @ConfigurationProperties("spring.datasource.druid.db1") public DataSource dataSource1() { return DruidDataSourceBuilder.create().build(); } @Bean("db2") @ConfigurationProperties("spring.datasource.druid.db2") public DataSource dataSource2() { return DruidDataSourceBuilder.create().build(); } @Bean @Primary public DataSource dataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); // 设置数据源映射关系 Map<Object, Object> dataSourceMap = new HashMap<>(); dataSourceMap.put("db1", dataSource1()); dataSourceMap.put("db2", dataSource2()); dynamicDataSource.setTargetDataSources(dataSourceMap); // 设置默认数据源 dynamicDataSource.setDefaultTargetDataSource(dataSource1()); return dynamicDataSource; } } ``` 4. 在Mapper配置类中使用@MapperScan(basePackages = {"com.test.mapper"})来扫描Mapper接口,并使用@DataSource注解来标注Mapper接口或方法。 ``` @Configuration @MapperScan(basePackages = {"com.test.mapper"}) public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } @DataSource("db1") public interface UserMapper { @Select("select * from user where id = #{id}") User selectById(@Param("id") Long id); } ``` 5. 实现AOP拦截数据源切换。 ``` @Aspect @Component public class DataSourceAspect { @Before("@annotation(ds)") public void beforeSwitchDataSource(JoinPoint point, DataSource ds) { String dataSource = ds.value(); if (!DynamicDataSourceContextHolder.containDataSourceKey(dataSource)) { System.err.println("数据源 " + dataSource + " 不存在,使用默认数据源"); } else { System.out.println("使用数据源:" + dataSource); DynamicDataSourceContextHolder.setDataSourceKey(dataSource); } } } ``` 6. 分页查询的使用示例: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override @DataSource("db1") public IPage<User> getUserList(int pageNum, int pageSize) { Page<User> page = new Page<>(pageNum, pageSize); return userMapper.selectPage(page, null); } } ``` 以上就是SpringBoot整合MyBatis-Plus实现多数据源的动态切换和分页查询的具体实现过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值