SpringBoot实现分页

背景

分页,在我们日常查询中使用频率非常高,这里就简单介绍一下springboot中常用的几种分页手段。

一、仅使用Mybatis

1、在Mapper接口中定义分页查询方法
在您的Mapper接口中,定义两个方法:一个用于查询分页数据,另一个用于查询总记录数。例如:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user LIMIT #{offset}, #{limit}")
    List<User> findAllWithPagination(@Param("offset") int offset, @Param("limit") int limit);

    @Select("SELECT COUNT(*) FROM user")
    int countTotalRecords();
}

2、在Service层中调用Mapper方法
在Service层中,调用Mapper方法并计算分页参数。例如:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return userMapper.findAllWithPagination(offset, pageSize);
    }

    public int countTotalRecords() {
        return userMapper.countTotalRecords();
    }
}

3、在Controller层中调用Service方法
在Controller层中,调用Service方法并返回分页结果。例如:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public Map<String, Object> getUsers(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        List<User> users = userService.findAllWithPagination(pageNum, pageSize);
        int totalRecords = userService.countTotalRecords();
        Map<String, Object> result = new HashMap<>();
        result.put("users", users);
        result.put("totalRecords", totalRecords);
        return result;
    }
}

二、使用Mybatis以及插件PageHelper

1、添加PageHelper依赖
在您的pom.xml文件中添加PageHelper依赖:

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>YourVersion</version>
</dependency>

2、配置PageHelper
在application.properties或application.yml文件中配置PageHelper:

# application.properties
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

# application.yml
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

3、在Mapper接口中使用PageHelper
在您的Mapper接口中,使用@Select注解编写查询语句,并在方法参数中添加RowBounds参数。例如:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.session.RowBounds;
import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user")
    List<User> findAllWithPagination(RowBounds rowBounds);
}

4、在Service层中调用Mapper方法
在Service层中,使用PageHelper.startPage()方法设置分页参数,然后调用Mapper方法。例如:

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public PageInfo<User> findAllWithPagination(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.findAllWithPagination();
        return new PageInfo<>(users);
    }
}

5、在Controller层中调用Service方法
在Controller层中,调用Service方法并返回分页结果。例如

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public PageInfo<User> getUsers(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return userService.findAllWithPagination(pageNum, pageSize);
    }
}

三、使用MybatisPlus

1、在Mapper中继承BaseMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserEntityMapper extends BaseMapper<UserEntity> {
    // 可以自定义查询方法
}

2、在Service类中注入该Mapper,并使用Mybatis Plus提供的Page类来进行分页查询。

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserEntityService {

    @Autowired
    private UserEntityMapper userEntityMapper;

    public IPage<UserEntity> listWithPage(int pageNum, int pageSize) {
        Page<UserEntity> page = new Page<>(pageNum, pageSize);
        return userEntityMapper.selectPage(page, null);
    }
}

3、最后,在Controller中调用Service的方法来获取分页数据,并将其返回给前端:

@RestController
public class UserEntityController {

    @Autowired
    private UserEntityService userEntityService;

    @GetMapping("/list")
    public IPage<UserEntity> listWithPage(
            @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) {
        return userEntityService.listWithPage(pageNum, pageSize);
    }
}

最后

以上就是Springboot的常用几种分页,简单记录一下。

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SpringBoot中使用分页功能可以借助MyBatis-Plus、Spring Data JPA等框架来实现。以下是使用MyBatis-Plus实现分页的示例: 1. 引入MyBatis-Plus依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> ``` 2. 创建实体类和对应的Mapper接口: ```java public class User { private Long id; private String name; private Integer age; // getter和setter省略 } public interface UserMapper extends BaseMapper<User> {} ``` 3. 在Mapper接口中定义方法: ```java public interface UserMapper extends BaseMapper<User> { IPage<User> selectUserPage(Page<User> page, @Param("name") String name); } ``` 4. 在对应的XML文件中实现方法: ```xml <select id="selectUserPage" resultType="com.example.demo.entity.User"> select id, name, age from user <where> <if test="name != null"> and name like concat('%', #{name}, '%') </if> </where> </select> ``` 5. 在Service层中调用Mapper接口方法: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public IPage<User> selectUserPage(Page<User> page, String name) { return userMapper.selectUserPage(page, name); } } ``` 6. 在Controller层中调用Service层方法: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public IPage<User> selectUserPage(Page<User> page, String name) { return userService.selectUserPage(page, name); } } ``` 这样就完成了使用MyBatis-Plus实现SpringBoot分页的示例。其中,`Page<User>`是MyBatis-Plus提供的分页查询参数封装类,`IPage<User>`是MyBatis-Plus提供的分页查询结果封装类。在Controller层中,通过接收`Page<User>`参数来传递分页查询的相关参数,同时也可以传递其他的查询参数,比如上述示例中的`name`参数。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值