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

   2024-10-01 2170
核心提示:要在Spring Boot中使用MyBatis的分页功能,可以按照以下步骤进行操作:在pom.xml文件中添加MyBatis和MyBatis分页插件的依赖:dep

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

在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>
在application.properties文件中配置MyBatis和分页插件的相关属性:
mybatis.mapper-locations=classpath:mapper/*.xmlpagehelper.helperDialect=mysqlpagehelper.reasonable=truepagehelper.supportMethodsArguments=true
在MyBatis的Mapper接口中定义查询方法,并在方法参数中添加PageHelper的相关参数:
import com.github.pagehelper.Page;import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapperpublic interface UserMapper {    List<User> selectAll(Page<User> page);}
在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;@Servicepublic 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);    }}
在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;@RestControllerpublic 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层的方法查询相应页的数据,并返回给前端页面展示。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号