SpringBoot 使用 mybatis-plus 实现分页功能

1. pom.xml 引入 mybatis-plus 依赖

        <!--        mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

2.在application.yml配置mybatis和mybatis-plus

mybatis:
  mapper-locations: classpath:mapper/*.xml  #根目录下的 mapper 目录中加载所有的 XML 文件。
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #配置 MyBatis-Plus 使用的日志实现。

3.创建 MybatisPlusConfig 配置类

@Configuration
public class MybatisPlusConfig {
    /**
     * MybatisPlus分页插件配置类
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

}

4. mapper 接口继承 BaseMapper<User>

@Mapper
public interface UserMapper extends BaseMapper<User> {

}

5.service接口 继承 IService<User>

public interface IUserService extends IService<User> {

}

6.service接口实现类 继承 ServiceImpl<UserMapper,User>

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

}

7.Controller 里使用 mybatis-plus 实现分页及模糊查询效果

@RestController
@RequestMapping("/user")
public class UserController {

    //注入 IUserService 接口
    @Autowired
    private IUserService userService;

    //分页查询
    @GetMapping("/page")
    public Page<User> page(@RequestParam Integer pageName,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name){
        //添加模糊查询条件
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (!"".equals(name)){
            userQueryWrapper.like("name",name);
        }
        //通过使用userService的mybatis-plus方法实现分页
        return userService.page(new Page<>(pageName,pageSize),userQueryWrapper);
    }


}

运行结果:

不加模糊查询

加模糊查询

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值