springboot+mybatis实现数据分页(三种方式)
項目準備
1.創建用戶表
2.使用spring初始化向導快速創建項目,勾選mybatis,web,jdbc,driver
添加lombok插件
一、使用原生Java實現分頁
1.UserMapper接口
@Mapper @Repository public interface UserMapper {int selectCount();List<User> selectUserFindAll(); }2.整合mybatis(application.yaml)
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/crud?serverTimezone=UTCusername: rootpassword: hao20001010mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.hao.springboot.entity3.測試dao層(成功)
@SpringBootTest class SpringBootCrudEndApplicationTests {@AutowiredUserMapper userMapper;@Testvoid contextLoads() {List<User> users = userMapper.selectUserFindAll();for(User user:users){System.out.println(user);}}@Testvoid contextLoads2(){} }4.編寫service層
public interface UserService {int selectCount();List<User> selectUserByArray(int currentPage,int pageSize); } /*** @author:抱著魚睡覺的喵喵* @date:2020/12/26* @description:*/ @Service public class UserServiceImpl implements UserService {@AutowiredUserMapper userMapper;@Overridepublic int selectCount() {int count = userMapper.selectCount();return count;}/*** 原始分頁邏輯實現* @param currentPage 當前頁* @param pageSize 每頁的數量* @return*/@Overridepublic List<User> selectUserByArray(int currentPage, int pageSize) {List<User> users = userMapper.selectUserFindAll();int count=selectCount();int startCurrentPage=(currentPage-1)*pageSize; //開啟的數據int endCurrentPage=currentPage*pageSize; //結束的數據int totalPage=count/pageSize; //總頁數if (currentPage>totalPage || currentPage<=0){return null;}else{return users.subList(startCurrentPage,endCurrentPage);}} }5.controller層
@RestController public class UserController {@AutowiredUserService userService;@GetMapping("/user/{currentPage}/{pageSize}")public List<User> selectFindPart(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize){List<User> list = userService.selectUserByArray(currentPage, pageSize);if (list==null){throw new UserNotExistException("訪問出錯!QWQ");}else{return list;}} }6.異常處理
public class UserNotExistException extends RuntimeException{private static final long serialVersionUID = 1L;private String msg;public UserNotExistException(String msg) {super("user not exist");this.msg=msg;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;} }7.controller異常處理類
/*** @author:抱著魚睡覺的喵喵* @date:2020/12/26* @description:*/ @ControllerAdvice //處理controller層出現的異常 public class ControllerExceptionHandler {@ExceptionHandler(UserNotExistException.class)@ResponseBody@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) //狀態碼public Map<String,Object> handlerUserNotExistException(UserNotExistException ex){Map<String,Object> result=new HashMap<>();result.put("msg", ex.getMsg());result.put("message", ex.getMessage());return result;} }8.訪問http://localhost:8080/user/5/10出現如下
{“msg”:“訪問出錯!QWQ”,“message”:“user not exist”}
9.訪問http://localhost:8080/user/2/3 出現如下
[{“id”:4,“userName”:“sky”,“password”:“789”},{“id”:5,“userName”:“nulls”,“password”:“tom”},{“id”:6,“userName”:“zsh”,“password”:“zsh”}]
總結:
缺點:數據庫查詢并返回所有的數據,而我們需要的只是極少數符合要求的數據。當數據量少時,還可以接受。當數據庫數據量過大時,每次查詢對數據庫和程序的性能都會產生極大的影響。
二、通過sql語句進行分頁操作
1.在UserMapper接口中新增一個方法
@Mapper @Repository public interface UserMapper {//原生分頁int selectCount();List<User> selectUserFindAll(); //通過sql語句進行分頁List<User> selectBySql(Map<String,Object> map); }2.UserService接口中新增方法,以及UserServiceImpl類中進行重寫
public interface UserService {int selectCount();/*** 原生分頁* @param currentPage* @param pageSize* @return*/List<User> selectUserByArray(int currentPage,int pageSize);/*** 通過sql分頁* @param currentPage* @param pageSize* @return*/List<User> selectUserBySql(int currentPage,int pageSize); } @Service public class UserServiceImpl implements UserService {@AutowiredUserMapper userMapper;@Overridepublic int selectCount() {int count = userMapper.selectCount();return count;}/*** 原始分頁邏輯實現* @param currentPage* @param pageSize* @return*/@Overridepublic List<User> selectUserByArray(int currentPage, int pageSize) {List<User> users = userMapper.selectUserFindAll();int count=selectCount();int startCurrentPage=(currentPage-1)*pageSize; //從第幾個數據開始int endCurrentPage=currentPage*pageSize; //結束的數據int totalPage=count/pageSize; //總頁數if (currentPage>totalPage || currentPage<=0){return null;}else{return users.subList(startCurrentPage,endCurrentPage);}} /** *通過sql語句進行分頁 */@Overridepublic List<User> selectUserBySql(int currentPage, int pageSize) {Map<String,Object> map=new HashMap<>();int startCurrentPage=(currentPage-1)*pageSize; //從第幾個數據開始int count=selectCount();int totalPage=count/pageSize; //總頁數if (currentPage>totalPage || currentPage<=0){return null;}else{map.put("currentPage",startCurrentPage);map.put("pageSize",pageSize);List<User> list = userMapper.selectBySql(map);return list;}} }3.controller層編寫
@RestController public class UserController {@AutowiredUserService userService; //Java原生實現分頁模塊@GetMapping("/user/{currentPage}/{pageSize}")public List<User> selectFindByJava(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize){List<User> list = userService.selectUserByArray(currentPage, pageSize);if (list==null){throw new UserNotExistException("訪問出錯!QWQ");}else{return list;}} //sql分頁方法模塊@GetMapping("/user2/{currentPage}/{pageSize}")public List<User> selectFindBySql(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize){List<User> list = userService.selectUserBySql(currentPage,pageSize);if (list==null){throw new UserNotExistException("訪問出錯!QWQ");}else{return list;}} }4.UserMapper.xml添加查詢條件,使用limit進行分頁
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.hao.springboot.mapper.UserMapper"><resultMap id="user" type="com.hao.springboot.entity.User"><result column="user_name" property="userName"/><result column="password" property="password"/></resultMap><select id="selectUserFindAll" resultMap="user">select * from user</select><select id="selectCount" resultType="integer">select count(*) from user</select><select id="selectBySql" parameterType="map" resultType="com.hao.springboot.entity.User">select * from user limit #{currentPage} , #{pageSize}</select> </mapper>5.啟動訪問http://localhost:8080/user2/5/10 出現如下
{“msg”:“訪問出錯!QWQ”,“message”:“user not exist”}
接著正確訪問http://localhost:8080/user2/2/2
[{“id”:3,“userName”:“tom”,“password”:“456”},{“id”:4,“userName”:“sky”,“password”:“789”}]
總結:
缺點:雖然這里實現了按需查找,每次檢索得到的是指定的數據。但是每次在分頁的時候都需要去編寫limit語句,很冗余。而且不方便統一管理,維護性較差。所以我們希望能夠有一種更方便的分頁實現。
三、攔截器實現分頁
總結
以上是生活随笔為你收集整理的springboot+mybatis实现数据分页(三种方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【SpringBoot】SpringBo
- 下一篇: Shiro之权限管理的概念