要在Spring Boot中使用MyBatis的分页功能,可以按照以下步骤进行操作:
- 在pom.xml文件中添加MyBatis和MyBatis分页插件的依赖:
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.4 com.github.pagehelper pagehelper 5.2.1
- 在application.properties文件中配置MyBatis和分页插件的相关属性:
mybatis.mapper-locations=classpath:mapper/*.xml pagehelper.helperDialect=mysql pagehelper.reasonable=true pagehelper.supportMethodsArguments=true
- 在MyBatis的Mapper接口中定义查询方法,并在方法参数中添加PageHelper的相关参数:
import com.github.pagehelper.Page; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface UserMapper { ListselectAll(Page 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; @Service public class UserService { @Autowired private UserMapper userMapper; public ListgetAllUsers(int pageNum, int pageSize) { Page 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; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public ListgetUsers(@RequestParam int pageNum, @RequestParam int pageSize) { return userService.getAllUsers(pageNum, pageSize); } }
通过以上步骤,就可以在Spring Boot中使用MyBatis的分页功能了。在Controller层中传入pageNum和pageSize参数,调用Service层的方法查询相应页的数据,并返回给前端页面展示。