SpringBoot中使用MyBatis-Plus實(shí)現(xiàn)分頁(yè)接口的詳細(xì)教程
MyBatis-Plus分頁(yè)接口實(shí)現(xiàn)教程:Spring Boot中如何編寫(xiě)分頁(yè)查詢(xún)
MyBatis-Plus 是一個(gè) MyBatis 的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。它提供了強(qiáng)大的分頁(yè)插件,可以輕松實(shí)現(xiàn)分頁(yè)查詢(xún)的功能。在 Spring Boot 項(xiàng)目中使用 MyBatis-Plus 可以大大簡(jiǎn)化分頁(yè)邏輯的編寫(xiě)。本文將介紹如何在 Spring Boot 項(xiàng)目中使用 MyBatis-Plus 實(shí)現(xiàn)分頁(yè)接口。
MyBatis-Plus 簡(jiǎn)介
MyBatis-Plus(簡(jiǎn)稱(chēng) MP)是 MyBatis 的一個(gè)增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。它提供了代碼生成器、分頁(yè)插件、性能分析插件、全局通用操作、MetaObject 等一系列功能,使得 MyBatis 變得更加易用。
Spring Boot 簡(jiǎn)介
Spring Boot 是 Spring 的一個(gè)模塊,用于簡(jiǎn)化新 Spring 應(yīng)用的初始搭建以及開(kāi)發(fā)過(guò)程。Spring Boot 旨在簡(jiǎn)化配置,通過(guò)約定大于配置的原則,提供了大量的默認(rèn)配置,使得開(kāi)發(fā)者能夠快速啟動(dòng)和部署 Spring 應(yīng)用。
實(shí)現(xiàn)步驟
1. 添加 MyBatis-Plus 依賴(lài)
在 pom.xml
文件中添加 MyBatis-Plus 的依賴(lài):
<!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.1</version> </dependency>
Springboot只能使用3.1.5及以下版本?。?!
2. 配置分頁(yè)插件
在 Spring Boot 的配置類(lèi)中添加分頁(yè)插件的配置:
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration //@MapperScan("com.example.demo.mapper") public class MybatisPlusConfig { /** * 新增分頁(yè)攔截器,并設(shè)置數(shù)據(jù)庫(kù)類(lèi)型為mysql * * @return */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
3. 創(chuàng)建服務(wù)層接口
創(chuàng)建一個(gè)服務(wù)層接口,用于定義分頁(yè)查詢(xún)的方法:
@Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public Result listPageUser(@RequestParam Integer page, @RequestParam Integer pageSize) { //分頁(yè)參數(shù) Page<UserEntity> rowPage = new Page<>(page, pageSize); //queryWrapper組裝查詢(xún)where條件 LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>(); rowPage = userMapper.selectPage(rowPage, queryWrapper); return Result.success("數(shù)據(jù)列表", rowPage); } }
4. 創(chuàng)建控制器
創(chuàng)建一個(gè)控制器,用于處理 HTTP 請(qǐng)求并調(diào)用服務(wù)層的分頁(yè)查詢(xún)方法:
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserServiceImpl userServiceImpl; @PostMapping("/listPage") @Operation(summary = "列表分頁(yè)") public Result listPageUser(@RequestParam Integer page, @RequestParam Integer pageSize) { return userServiceImpl.listPageUser(page, pageSize); } }
5. 運(yùn)行應(yīng)用并測(cè)試
啟動(dòng) Spring Boot 應(yīng)用,并通過(guò) Postman 或其他 API 測(cè)試工具發(fā)送 POST 請(qǐng)求到 /user/listPage
端點(diǎn),傳遞 page
和 pageSize
參數(shù),即可測(cè)試分頁(yè)查詢(xún)功能。
6.全部代碼
import com.alibaba.excel.EasyExcel; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.common.req.IdParam; import com.example.common.resp.Result; import com.example.system.entity.UserEntity; import com.example.system.mapper.UserMapper; import com.example.system.resp.LoginResp; import com.example.system.service.UserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Objects; /** * <p> * 用戶(hù)表 前端控制器 * </p> * * @author he * @since 2024-03-23 */ @Tag(name = "用戶(hù)") @RestController @RequestMapping("/userEntity") public class UserController { @Autowired private UserMapper userMapper; @Autowired private UserService userService; private final String id = "User_id"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Operation(summary = "列表") @PostMapping("/list") public Result listUser() { return Result.success("數(shù)據(jù)列表", userService.list()); } @Operation(summary = "存在") @PostMapping("/exist") public Result existUser(@RequestBody @Validated IdParam param) { QueryWrapper<UserEntity> wrapper = new QueryWrapper<>(); wrapper.eq(id.toLowerCase(Locale.ROOT), param.getId()); long count = userService.count(wrapper); if (count == 0) return Result.success("ID不存在", false); return Result.success("ID已存在", true); } @Operation(summary = "保存") @PostMapping("/insert") public Result insertUser(@RequestBody @Validated UserEntity param) { QueryWrapper<UserEntity> wrapper = new QueryWrapper<>(); wrapper.eq(id.toLowerCase(Locale.ROOT), param.getId()); if (userService.count(wrapper) != 0) return Result.failure("ID已存在", sdf.format(new Date())); if (userService.save(param)) return Result.success("保存成功", sdf.format(new Date())); return Result.failure("保存失敗", sdf.format(new Date())); } @Operation(summary = "刪除") @PostMapping("/delete") public Result deleteUser(@RequestBody @Validated IdParam param) { QueryWrapper<UserEntity> wrapper = new QueryWrapper<>(); wrapper.eq(id.toLowerCase(Locale.ROOT), param.getId()); if (userService.count(wrapper) == 0) return Result.failure("ID不存在", param.getId()); if (userService.remove(wrapper)) return Result.success("刪除成功", param.getId()); return Result.failure("刪除失敗", param.getId()); } @Operation(summary = "修改") @PostMapping("/update") public Result updateUser(@RequestBody @Validated UserEntity param) { QueryWrapper<UserEntity> wrapper = new QueryWrapper<>(); wrapper.eq(id.toLowerCase(Locale.ROOT), param.getId()); if (userService.count(wrapper) == 0) return Result.failure("ID不存在", sdf.format(new Date())); if (userService.updateById(param)) return Result.success("修改成功", sdf.format(new Date())); return Result.failure("修改失敗", sdf.format(new Date())); } @Operation(summary = "查詢(xún)") @PostMapping("/select") public Result selectUser(@RequestBody @Validated IdParam param) { QueryWrapper<UserEntity> wrapper = new QueryWrapper<>(); wrapper.eq(id.toLowerCase(Locale.ROOT), param.getId()); if (userService.count(wrapper) == 0) return Result.failure("ID不存在", param.getId()); return Result.success(userService.getOne(wrapper)); } @Operation(summary = "查詢(xún)byAcc") @PostMapping("/selectByAcc/{param}") public Result selectUserByAcc(@PathVariable @Validated String param) { QueryWrapper<UserEntity> wrapper = new QueryWrapper<>(); String acc = "User_acc"; wrapper.eq(acc.toLowerCase(Locale.ROOT), param); if (userService.count(wrapper) == 0) return Result.failure("賬號(hào)不存在", sdf.format(new Date())); return Result.success(userService.getOne(wrapper)); } @Operation(summary = "列表分頁(yè)") @PostMapping("/listPage") public Result listPageUser(@RequestParam Integer page, @RequestParam Integer pageSize) { //分頁(yè)參數(shù) Page<UserEntity> rowPage = new Page(page, pageSize); //queryWrapper組裝查詢(xún)where條件 LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>(); rowPage = userMapper.selectPage(rowPage, queryWrapper); return Result.success("數(shù)據(jù)列表", rowPage); } @Operation(summary = "導(dǎo)出數(shù)據(jù)") @PostMapping("exportExcel") public void exportExcelUser(HttpServletResponse response) throws IOException { response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("輪播圖", StandardCharsets.UTF_8).replaceAll("\\+", "%20"); List<UserEntity> list = userService.list(); response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx"); EasyExcel.write(response.getOutputStream(), UserEntity.class).sheet("輪播圖").doWrite(list); } @Operation(summary = "導(dǎo)入數(shù)據(jù)") @PostMapping("/importExcel") public Result importExcelUser(MultipartFile file) { try { //獲取文件的輸入流 InputStream inputStream = file.getInputStream(); List<UserEntity> list = EasyExcel.read(inputStream) //調(diào)用read方法 //注冊(cè)自定義監(jiān)聽(tīng)器,字段校驗(yàn)可以在監(jiān)聽(tīng)器內(nèi)實(shí)現(xiàn) //.registerReadListener(new UserListener()) .head(UserEntity.class) //對(duì)應(yīng)導(dǎo)入的實(shí)體類(lèi) .sheet(0) //導(dǎo)入數(shù)據(jù)的sheet頁(yè)編號(hào),0代表第一個(gè)sheet頁(yè),如果不填,則會(huì)導(dǎo)入所有sheet頁(yè)的數(shù)據(jù) .headRowNumber(1) //列表頭行數(shù),1代表列表頭有1行,第二行開(kāi)始為數(shù)據(jù)行 .doReadSync();//開(kāi)始讀Excel,返回一個(gè)List<T>集合,繼續(xù)后續(xù)入庫(kù)操作 //模擬導(dǎo)入數(shù)據(jù)庫(kù)操作 for (UserEntity entity : list) { userService.saveOrUpdate(entity); } return Result.success("導(dǎo)入成功", sdf.format(new Date())); } catch (IOException exception) { throw new RuntimeException(exception); } } }
結(jié)語(yǔ)
通過(guò)上述步驟,我們?cè)?Spring Boot 項(xiàng)目中使用 MyBatis-Plus 實(shí)現(xiàn)了一個(gè)分頁(yè)查詢(xún)接口。MyBatis-Plus 提供的分頁(yè)插件極大地簡(jiǎn)化了分頁(yè)邏輯的編寫(xiě),使得開(kāi)發(fā)者能夠更專(zhuān)注于業(yè)務(wù)邏輯的實(shí)現(xiàn)。通過(guò)學(xué)習(xí)和實(shí)踐,你可以更深入地理解 MyBatis-Plus 和 Spring Boot 的強(qiáng)大功能,以及如何將它們應(yīng)用到實(shí)際的開(kāi)發(fā)工作中。
以上就是SpringBoot中使用MyBatis-Plus實(shí)現(xiàn)分頁(yè)接口的詳細(xì)教程的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot MyBatis-Plus分頁(yè)接口的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot同時(shí)集成Mybatis和Mybatis-plus框架
- SpringBoot+MyBatis-Plus實(shí)現(xiàn)分頁(yè)示例
- Springboot整合mybatis-plus使用pageHelper進(jìn)行分頁(yè)(使用步驟)
- SpringBoot+MyBatis-Plus實(shí)現(xiàn)分頁(yè)的項(xiàng)目實(shí)踐
- springboot集成mybatis-plus全過(guò)程
- Springboot集成Mybatis-plus、ClickHouse實(shí)現(xiàn)增加數(shù)據(jù)、查詢(xún)數(shù)據(jù)功能
- springboot項(xiàng)目中mybatis-plus@Mapper注入失敗問(wèn)題
- springboot+mybatis-plus實(shí)現(xiàn)自動(dòng)建表的示例
- SpringBoot?mybatis-plus使用json字段實(shí)戰(zhàn)指南
- springboot3.2整合mybatis-plus詳細(xì)代碼示例
- 全網(wǎng)最新springboot整合mybatis-plus的過(guò)程
相關(guān)文章
AbstractQueuedSynchronizer內(nèi)部類(lèi)Node使用講解
這篇文章主要為大家介紹了AbstractQueuedSynchronizer內(nèi)部類(lèi)Node使用講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07Spring將MultipartFile轉(zhuǎn)存到本地磁盤(pán)的三種方式
在Java中處理文件向來(lái)是一種不是很方便的操作,然后隨著Spring框架的崛起,使用Spring框架中的MultipartFile來(lái)處理文件也是件很方便的事了,今天就給大家介紹Spring將MultipartFile轉(zhuǎn)存到本地磁盤(pán)的方式,需要的朋友可以參考下2024-10-10kafka topic 權(quán)限控制(設(shè)置刪除權(quán)限)
大家都知道Kafka是一個(gè)消息隊(duì)列,把消息放到隊(duì)列里邊的叫生產(chǎn)者,從隊(duì)列里邊消費(fèi)的叫消費(fèi)者。今天通過(guò)本文給大家介紹kafka topic 權(quán)限控制的相關(guān)知識(shí),感興趣的朋友一起看看吧2021-11-11Java調(diào)用wsdl接口的兩種方法(axis和wsimport)
本文主要介紹了Java調(diào)用wsdl接口的兩種方法(axis和wsimport),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03SpringBoot3 Spring WebFlux簡(jiǎn)介(推薦)
SpringWebFlux是Spring Framework 5中引入的響應(yīng)式Web框架,用于支持非阻塞異步通信和響應(yīng)式流處理,與傳統(tǒng)的SpringMVC相比,WebFlux提供了完全異步非阻塞的編程模型,適用高并發(fā)、微服務(wù)架構(gòu)和實(shí)時(shí)數(shù)據(jù)流,本文介紹SpringBoot3 Spring WebFlux簡(jiǎn)介,感興趣的朋友一起看看吧2024-10-10實(shí)例詳解Java實(shí)現(xiàn)圖片與base64字符串之間的轉(zhuǎn)換
這篇文章主要介紹了Java實(shí)現(xiàn)圖片與base64字符串之間的轉(zhuǎn)換實(shí)例代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下2016-12-12使用迭代器模式來(lái)進(jìn)行Java的設(shè)計(jì)模式編程
這篇文章主要介紹了使用迭代器模式來(lái)進(jìn)行Java的設(shè)計(jì)模式編程,文中對(duì)迭代器模式中的容器封裝方面的知識(shí)進(jìn)行了講解,需要的朋友可以參考下2016-02-02SpringBoot動(dòng)態(tài)修改yml配置文件的方法詳解
這篇文章主要為大家詳細(xì)介紹了SpringBoot動(dòng)態(tài)修改yml配置文件的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-03-03