Spring Boot

如何在Spring Boot中使用MyBatis的分页功能

小樊
82
2024-08-12 21:27:42
栏目: 编程语言

要在Spring Boot中使用MyBatis的分页功能,可以按照以下步骤进行操作:

  1. 在pom.xml文件中添加MyBatis和MyBatis分页插件的依赖:
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.1</version>
</dependency>
  1. 在application.properties文件中配置MyBatis和分页插件的相关属性:
mybatis.mapper-locations=classpath:mapper/*.xml
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
  1. 在MyBatis的Mapper接口中定义查询方法,并在方法参数中添加PageHelper的相关参数:
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface UserMapper {
    List<User> selectAll(Page<User> page);
}
  1. 在Service层中调用Mapper接口的方法,传入PageHelper的参数:
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    public List<User> getAllUsers(int pageNum, int pageSize) {
        Page<User> page = PageHelper.startPage(pageNum, pageSize);
        return userMapper.selectAll(page);
    }
}
  1. 在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.List;

@RestController
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/users")
    public List<User> getUsers(@RequestParam int pageNum, @RequestParam int pageSize) {
        return userService.getAllUsers(pageNum, pageSize);
    }
}

通过以上步骤,就可以在Spring Boot中使用MyBatis的分页功能了。在Controller层中传入pageNum和pageSize参数,调用Service层的方法查询相应页的数据,并返回给前端页面展示。

0
看了该问题的人还看了