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

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

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

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)文章!

相關(guān)文章

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

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

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

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

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

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

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

    JSON Web Token在登陸中的使用過(guò)程

    這篇文章主要介紹了JSON Web Token在登陸中的使用過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    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è)計(jì)采用策略模式實(shí)現(xiàn)各支付渠道(微信、支付寶、銀聯(lián))的統(tǒng)一接口,通過(guò)工廠模式動(dòng)態(tài)創(chuàng)建支付策略,感興趣的可以了解一下
    2026-03-03
  • 使用Lombok時(shí)@JsonIgnore注解失效解決方案

    使用Lombok時(shí)@JsonIgnore注解失效解決方案

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

    淺談Springboot整合RocketMQ使用心得

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

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

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

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

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

最新評(píng)論

玉山县| 娄底市| 汉沽区| 京山县| 临澧县| 松溪县| 商河县| 天台县| 南乐县| 修武县| 太仆寺旗| 濮阳县| 沙湾县| 游戏| 木兰县| 政和县| 河南省| 普宁市| 陆川县| 武穴市| 沭阳县| 全州县| 白水县| 友谊县| 元江| 文安县| 顺义区| 灵丘县| 潼关县| 卓资县| 贵港市| 鹿泉市| 阳山县| 上栗县| 和政县| 西平县| 彰化县| 昌吉市| 沂南县| 鄂温| 鹿邑县|