最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot中使用MyBatis-Plus實(shí)現(xiàn)分頁接口的詳細(xì)教程

 更新時間:2024年03月29日 09:09:55   作者:洛可可白  
MyBatis-Plus是一個MyBatis的增強(qiáng)工具,在MyBatis的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生,在SpringBoot項(xiàng)目中使用MyBatis-Plus可以大大簡化分頁邏輯的編寫,本文將介紹如何在 SpringBoot項(xiàng)目中使用MyBatis-Plus實(shí)現(xiàn)分頁接口

MyBatis-Plus分頁接口實(shí)現(xiàn)教程:Spring Boot中如何編寫分頁查詢

MyBatis-Plus 是一個 MyBatis 的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生。它提供了強(qiáng)大的分頁插件,可以輕松實(shí)現(xiàn)分頁查詢的功能。在 Spring Boot 項(xiàng)目中使用 MyBatis-Plus 可以大大簡化分頁邏輯的編寫。本文將介紹如何在 Spring Boot 項(xiàng)目中使用 MyBatis-Plus 實(shí)現(xiàn)分頁接口。

MyBatis-Plus 簡介

MyBatis-Plus(簡稱 MP)是 MyBatis 的一個增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生。它提供了代碼生成器、分頁插件、性能分析插件、全局通用操作、MetaObject 等一系列功能,使得 MyBatis 變得更加易用。

Spring Boot 簡介

Spring Boot 是 Spring 的一個模塊,用于簡化新 Spring 應(yīng)用的初始搭建以及開發(fā)過程。Spring Boot 旨在簡化配置,通過約定大于配置的原則,提供了大量的默認(rèn)配置,使得開發(fā)者能夠快速啟動和部署 Spring 應(yīng)用。

實(shí)現(xiàn)步驟

1. 添加 MyBatis-Plus 依賴

在 pom.xml 文件中添加 MyBatis-Plus 的依賴:

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>

Springboot只能使用3.1.5及以下版本?。。?/p>

2. 配置分頁插件

在 Spring Boot 的配置類中添加分頁插件的配置:

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 {

    /**
     * 新增分頁攔截器,并設(shè)置數(shù)據(jù)庫類型為mysql
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

3. 創(chuàng)建服務(wù)層接口

創(chuàng)建一個服務(wù)層接口,用于定義分頁查詢的方法:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result listPageUser(@RequestParam Integer page, @RequestParam Integer pageSize) {
        //分頁參數(shù)
        Page<UserEntity> rowPage = new Page<>(page, pageSize);
        //queryWrapper組裝查詢where條件
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        rowPage = userMapper.selectPage(rowPage, queryWrapper);
        return Result.success("數(shù)據(jù)列表", rowPage);
    }
}

4. 創(chuàng)建控制器

創(chuàng)建一個控制器,用于處理 HTTP 請求并調(diào)用服務(wù)層的分頁查詢方法:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userServiceImpl;

    @PostMapping("/listPage")
    @Operation(summary = "列表分頁")
    public Result listPageUser(@RequestParam Integer page, @RequestParam Integer pageSize) {
        return userServiceImpl.listPageUser(page, pageSize);
    }
}

5. 運(yùn)行應(yīng)用并測試

啟動 Spring Boot 應(yīng)用,并通過 Postman 或其他 API 測試工具發(fā)送 POST 請求到 /user/listPage 端點(diǎn),傳遞 page 和 pageSize 參數(shù),即可測試分頁查詢功能。

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>
 * 用戶表 前端控制器
 * </p>
 *
 * @author he
 * @since 2024-03-23
 */
@Tag(name = "用戶")
@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 = "查詢")
    @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 = "查詢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("賬號不存在", sdf.format(new Date()));
        return Result.success(userService.getOne(wrapper));
    }

    @Operation(summary = "列表分頁")
    @PostMapping("/listPage")
    public Result listPageUser(@RequestParam Integer page, @RequestParam Integer pageSize) {
        //分頁參數(shù)
        Page<UserEntity> rowPage = new Page(page, pageSize);
        //queryWrapper組裝查詢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方法
                    //注冊自定義監(jiān)聽器,字段校驗(yàn)可以在監(jiān)聽器內(nèi)實(shí)現(xiàn)
                    //.registerReadListener(new UserListener())
                    .head(UserEntity.class) //對應(yīng)導(dǎo)入的實(shí)體類
                    .sheet(0) //導(dǎo)入數(shù)據(jù)的sheet頁編號,0代表第一個sheet頁,如果不填,則會導(dǎo)入所有sheet頁的數(shù)據(jù)
                    .headRowNumber(1) //列表頭行數(shù),1代表列表頭有1行,第二行開始為數(shù)據(jù)行
                    .doReadSync();//開始讀Excel,返回一個List<T>集合,繼續(xù)后續(xù)入庫操作
            //模擬導(dǎo)入數(shù)據(jù)庫操作
            for (UserEntity entity : list) {
                userService.saveOrUpdate(entity);
            }
            return Result.success("導(dǎo)入成功", sdf.format(new Date()));
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

}

結(jié)語

通過上述步驟,我們在 Spring Boot 項(xiàng)目中使用 MyBatis-Plus 實(shí)現(xiàn)了一個分頁查詢接口。MyBatis-Plus 提供的分頁插件極大地簡化了分頁邏輯的編寫,使得開發(fā)者能夠更專注于業(yè)務(wù)邏輯的實(shí)現(xiàn)。通過學(xué)習(xí)和實(shí)踐,你可以更深入地理解 MyBatis-Plus 和 Spring Boot 的強(qiáng)大功能,以及如何將它們應(yīng)用到實(shí)際的開發(fā)工作中。

以上就是SpringBoot中使用MyBatis-Plus實(shí)現(xiàn)分頁接口的詳細(xì)教程的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot MyBatis-Plus分頁接口的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • ShardingProxy讀寫分離之原理、配置與實(shí)踐過程

    ShardingProxy讀寫分離之原理、配置與實(shí)踐過程

    ShardingProxy是Apache?ShardingSphere的數(shù)據(jù)庫中間件,通過三層架構(gòu)實(shí)現(xiàn)讀寫分離,解決高并發(fā)場景下數(shù)據(jù)庫性能瓶頸,其核心功能包括SQL路由、負(fù)載均衡、數(shù)據(jù)一致性保障和故障轉(zhuǎn)移,支持主從架構(gòu)下的透明分庫分表及讀寫分流,廣泛應(yīng)用于微服務(wù)和高流量業(yè)務(wù)系統(tǒng)
    2025-08-08
  • Mybatis-Plus實(shí)現(xiàn)用戶ID自增出現(xiàn)的問題解決

    Mybatis-Plus實(shí)現(xiàn)用戶ID自增出現(xiàn)的問題解決

    項(xiàng)目基于 SpringBoot + MybatisPlus 3.5.2 使用數(shù)據(jù)庫自增ID時, 出現(xiàn)重復(fù)鍵的問題,本文就來介紹一下解決方法,感興趣的可以了解一下
    2023-09-09
  • java實(shí)現(xiàn)對excel文件的處理合并單元格的操作

    java實(shí)現(xiàn)對excel文件的處理合并單元格的操作

    這篇文章主要介紹了java實(shí)現(xiàn)對excel文件的處理合并單元格的操作,開頭給大家介紹了依賴引入代碼,表格操作的核心代碼,代碼超級簡單,需要的朋友可以參考下
    2021-07-07
  • JSON Web Token在登陸中的使用過程

    JSON Web Token在登陸中的使用過程

    這篇文章主要介紹了JSON Web Token在登陸中的使用過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • Java中雙向鏈表詳解及實(shí)例

    Java中雙向鏈表詳解及實(shí)例

    這篇文章主要介紹了Java中雙向鏈表詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • SpringBoot?支付渠道實(shí)現(xiàn)統(tǒng)一的支付服務(wù)示例

    SpringBoot?支付渠道實(shí)現(xiàn)統(tǒng)一的支付服務(wù)示例

    本文提出了一種基于工廠模式和策略模式的多渠道支付封裝方案,該設(shè)計采用策略模式實(shí)現(xiàn)各支付渠道(微信、支付寶、銀聯(lián))的統(tǒng)一接口,通過工廠模式動態(tài)創(chuàng)建支付策略,感興趣的可以了解一下
    2026-03-03
  • 使用Lombok時@JsonIgnore注解失效解決方案

    使用Lombok時@JsonIgnore注解失效解決方案

    這篇文章主要為大家介紹了使用Lombok時@JsonIgnore注解失效問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • 淺談Springboot整合RocketMQ使用心得

    淺談Springboot整合RocketMQ使用心得

    本篇文章主要介紹了Springboot整合RocketMQ使用心得,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • springBoot詳細(xì)講解使用mybaties案例

    springBoot詳細(xì)講解使用mybaties案例

    MyBatis本是apache的一個開源項(xiàng)目iBatis,2010年這個項(xiàng)目由apache software foundation遷移到了google code,并且改名為MyBatis。2013年11月遷移到Github。iBATIS一詞來源于“internet”和“abatis”的組合,是一個基于Java的持久層框架
    2022-05-05
  • Spring Boot 中的靜態(tài)資源放置位置

    Spring Boot 中的靜態(tài)資源放置位置

    這篇文章主要介紹了Spring Boot 中的靜態(tài)資源到底要存放哪里,很多童鞋對這個問題很糾結(jié),接下來通過本文給大家介紹下,需要的朋友可以參考下
    2019-04-04

最新評論

澳门| 舟曲县| 泌阳县| 郎溪县| 石家庄市| 万全县| 梧州市| 莫力| 嘉黎县| 沁水县| 旬阳县| 海阳市| 固阳县| 阳山县| 涞源县| 枣阳市| 稷山县| 郁南县| 苍溪县| 视频| 宾阳县| 河源市| 阳原县| 彰化县| 麻城市| 贵溪市| 西林县| 蓝田县| 五指山市| 顺义区| 达日县| 沾益县| 崇信县| 新平| 漾濞| 留坝县| 深水埗区| 赣州市| 金华市| 凤阳县| 丰城市|