亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁(yè)查詢功能

 更新時(shí)間:2023年11月14日 15:31:03   作者:Blet-  
這篇文章主要介紹了SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁(yè)查詢功能,pringBoot分頁(yè)查詢的兩種寫(xiě)法,一種是手動(dòng)實(shí)現(xiàn),另一種是使用框架實(shí)現(xiàn),現(xiàn)在我將具體的實(shí)現(xiàn)流程分享一下,需要的朋友可以參考下

一、前言

        最近學(xué)習(xí)了SpringBoot分頁(yè)查詢的兩種寫(xiě)法,一種是手動(dòng)實(shí)現(xiàn),另一種是使用框架實(shí)現(xiàn)?,F(xiàn)在我將具體的實(shí)現(xiàn)流程分享一下。

二、手動(dòng)實(shí)現(xiàn)分頁(yè)查詢

        先復(fù)習(xí)一下,SQL中的limit關(guān)鍵字,下面一行sql語(yǔ)句的意思是從第二個(gè)數(shù)據(jù)開(kāi)始查,查詢出兩條數(shù)據(jù)

SELECT * FROM map limit 1,2;

使用limit前一個(gè)參數(shù)pageNum是從第幾個(gè)數(shù)據(jù)開(kāi)始查,后一個(gè)參數(shù)pageSize是查詢多少條數(shù)據(jù),注意數(shù)據(jù)庫(kù)查詢pageNum=0代表第一個(gè)數(shù)據(jù)。

那么在Springboot中該如何寫(xiě)呢?

三、了解@RequestParam

1.什么是@RequestParam

@RequestParam:將請(qǐng)求參數(shù)綁定到你控制器的方法參數(shù)上(是springmvc中接收普通參數(shù)的注解)

 2.語(yǔ)法

語(yǔ)法:@RequestParam(value=”參數(shù)名”,required=”true/false”,defaultValue=””)

value:參數(shù)名

required:是否包含該參數(shù),默認(rèn)為true,表示該請(qǐng)求路徑中必須包含該參數(shù),如果不包含就報(bào)錯(cuò)。

defaultValue:默認(rèn)參數(shù)值,如果設(shè)置了該值,required=true將失效,自動(dòng)為false,如果沒(méi)有傳該參數(shù),就使用默認(rèn)值

3.測(cè)試環(huán)境

環(huán)境:jdk1.8 Tomcat8.5  idea2018  manven父工程子模塊

步驟:
1、創(chuàng)建web工程、引入依賴
2、配置SpringMvc入口文件 --DispatcherServlet--為總調(diào)度、web.xml里配置
3、創(chuàng)建Springmvc.xml文件--理解為:適配器(這里不需要自已指定適配、springmvc會(huì)自動(dòng)指定)--視圖解析器
4、創(chuàng)建 業(yè)務(wù)處理器 Controller類(lèi)
5、測(cè)試

四、了解QueryWrapper

1.QueryWrapper是什么?

        QueryWrapper就是在使用Mybatis-plus中真實(shí)用到的一種技術(shù),也叫作構(gòu)造器,能簡(jiǎn)化sql的操作。

2.常用方法總結(jié)

1、單表操作

代碼如下(示例):我要查詢姓名、班級(jí)、年齡符合前端傳過(guò)來(lái)參數(shù)的數(shù)據(jù)并進(jìn)行排序。

@GetMapping("/list")
public TableDataInfo list(Student student){
	LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper<Student>();
	lqw.eq(Student::getName, student.getName());
	lqw.like(Student::getClass,student.getClass());
	lqw.between("age",student.getAge1(),student.getAge2());
	lqw.orderByAsc("age");
	List<Student> list = studentService.list(lqw);
}

以上代碼對(duì)應(yīng)的sql為:

select * from student where name = '?' and class like '%?%' and age between '?' and '?' order by '?' asc

        由此可以看出,QueryWrapper其實(shí)可以理解成一個(gè)放查詢條件的盒子,我們把查詢條件放在里面,他就會(huì)自動(dòng)按照對(duì)應(yīng)的條件進(jìn)行查詢數(shù)據(jù)。

        根據(jù)不同的查詢要求,有不同的用法,常用到的比如:eq、like、and、or、isNull、isNotNull、ne、likeRight、between等;使用方法及說(shuō)明見(jiàn)下圖。

2、多表操作

//Controller
@GetMapping("/listAndClass")
public TableDataInfo listAndClass(Student student)
{
    QueryWrapper<Student > qw = new QueryWrapper<Student >();
    if(StringUtils.isNotBlank(student.getName())){
        qw.eq("s.name",student.getName());
    }
    if(StringUtils.isNotBlank(student.getClassName())){
        qw.like("c.name",student.getClassName());
    }
    startPage();
    List<Student > list = studentService.listAndClass(qw);
    return getDataTable(list);
}
//Service
 List<Student> listAndClass(QueryWrapper<Student> qw);
//Service impl
@Override
public List<Student> listAndClass(QueryWrapper<Student> qw) {
    return this.getBaseMapper().listAndClass(qw);
}
//Mapper
@Select("select s.*,c.name from student s left join class c on s.id = c.student_id "+
        "${ew.customSqlSegment}")
List<YwSpaqjgDj> listAndClass(@Param(Constants.WRAPPER) QueryWrapper<Student> qw);

五.SpringBoot實(shí)現(xiàn)分頁(yè)查詢

1.創(chuàng)建UserController

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Constants;
import com.example.demo.common.Result;
import com.example.demo.controller.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.service.IUserService;
import com.example.demo.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"參數(shù)錯(cuò)誤");
        }
        UserDTO dto = userService.login(userDTO);
        return Result.success(dto);
    }
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"參數(shù)錯(cuò)誤");
        }
        return Result.success(userService.register(userDTO));
    }
    //新增或者更新
    @PostMapping
    public Result save(@RequestBody User user) {
        String username = user.getUsername();
        if (StrUtil.isBlank(username)) {
            return Result.error(Constants.CODE_400, "參數(shù)錯(cuò)誤");
        }
        if (user.getId() != null) {
            user.setPassword(null);
        } else {
            user.setNickname(user.getUsername());
            if (user.getPassword() == null) {
                user.setPassword("123456");
            }
        }
        return Result.success(userService.saveOrUpdate(user));
    }
    //刪除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {//批量刪除
        return Result.success(userService.removeByIds(ids));
    }
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }
    @GetMapping("/username/{username}")
    public Result findOne(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(userService.getOne(queryWrapper));
    }
}

并在Controller里面寫(xiě)好page接口

@GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }
        return Result.success(userService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

不難看出我們是根據(jù)數(shù)據(jù)庫(kù)的id進(jìn)行查詢出數(shù)據(jù)庫(kù)的數(shù)據(jù)

queryWrapper.orderByDesc("id")

六、了解equals

1.什么是equals

        equals():equals是Object中的方法,用于檢測(cè)一個(gè)對(duì)象是否等于另一個(gè)對(duì)象,在Object中equals方法實(shí)際"ruturn (this==obj)",用到的還是"==",說(shuō)明如果對(duì)象不重寫(xiě)equals方法,實(shí)際該對(duì)象的equals和"=="作用是一樣的,都是比較的地址值(因?yàn)?quot;=="比較的就是地址值),但是大部分類(lèi)都會(huì)重寫(xiě)父類(lèi)的equals方法,用來(lái)檢測(cè)兩個(gè)對(duì)象是否相等,即兩個(gè)對(duì)象的內(nèi)容是否相等,例如String就重寫(xiě)了equals方法,用來(lái)比較兩個(gè)字符串內(nèi)容是否相同??匆韵麓a:

public static void main(String[] args) {
    Object o = new Object();   
    Object o1 = o;
    Object o2 = o;
    System.out.println(o3.equals(o2));
}

代碼輸出:true

        所以我們是使用 equals來(lái)確定我們查詢數(shù)據(jù)的對(duì)象,所以我們這里選擇使用username來(lái)查詢數(shù)據(jù)庫(kù)里面的具體數(shù)據(jù)

if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }

七、前端使用

1.前端技術(shù)棧

        對(duì)于前端,我們使用的是Vue+Element來(lái)進(jìn)行功能實(shí)現(xiàn),對(duì)于跨域的處理我使用的是axios進(jìn)行處理,并且對(duì)axios進(jìn)行了封裝,具體步驟請(qǐng)查看:解決SpringBoot和前端Vue的跨域問(wèn)題

2.組件使用

我選用的是Element官網(wǎng)的組件來(lái)進(jìn)行數(shù)據(jù)渲染

我們進(jìn)行組件使用,并且設(shè)置分頁(yè)的數(shù)據(jù)數(shù)量,數(shù)據(jù)可分為一頁(yè)5條、10條以及15條 

<div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[ 5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

3.數(shù)據(jù)渲染

我們默認(rèn)查詢處理的數(shù)據(jù)是0,設(shè)置頁(yè)數(shù)為一頁(yè),一頁(yè)為5條數(shù)據(jù)

data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      username: "",
      form: {},
      dialogFormVisible: false,
      multipleSelection: [],
      headerBg: "headerBg",
      roles: []
    }
  }

 最后進(jìn)行數(shù)據(jù)請(qǐng)求,請(qǐng)求后臺(tái)寫(xiě)好的page接口

methods: {
    load: function () {
      this.request.get("/user/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
      this.request.get("/role").then(res => {
        this.roles = res.data
      })
    }
}

八、功能展示 

最后附上前端完整代碼

<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px; margin-left: 10px" placeholder="請(qǐng)輸入用戶名" clearable suffix-icon="el-icon-user" v-model="username" ></el-input>
      <el-button class="ml-5" type="primary" @click="load"><i class="el-icon-search" />搜索</el-button>
      <el-button type="warning" @click="reset"><i class="el-icon-refresh" />刷新</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd" class="ml-10"><i class="el-icon-circle-plus-outline" />新增</el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='確認(rèn)'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="確定批量刪除這些信息嗎?"
          @confirm="delBatch">
        <el-button type="danger" slot="reference" ><i class="el-icon-remove-outline" />刪除</el-button>
      </el-popconfirm>
      <el-upload action="http://localhost:9090/user/import" :show-file-list="false" accept=".xlsx"
                 :on-success="handleExcelImportSuccess" style="display: inline-block">
        <el-button type="primary" class="ml-5"><i class="el-icon-upload"></i>導(dǎo)入</el-button>
      </el-upload>
      <el-button type="primary" class="ml-5" @click="exp"><i class="el-icon-download" />導(dǎo)出</el-button>
    </div>
    <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="username" label="用戶名" ></el-table-column>
      <el-table-column prop="nickname" label="昵稱" ></el-table-column>
      <el-table-column prop="email" label="郵箱" ></el-table-column>
      <el-table-column prop="phone" label="聯(lián)系方式" ></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
<!--      <el-table-column prop="role" label="身份"></el-table-column>-->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)"><i class="el-icon-edit-outline" />編輯</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[ 5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="用戶信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" label-width="100px" size="small">
        <el-form-item label="用戶名" >
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵稱" >
          <el-input v-model="form.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="郵箱" >
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="聯(lián)系方式" >
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" >
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">確 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "User",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      username: "",
      form: {},
      dialogFormVisible: false,
      multipleSelection: [],
      headerBg: "headerBg",
      roles: []
    }
  },
  created() {
    this.load()
  },
  methods: {
    load: function () {
      this.request.get("/user/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
      this.request.get("/role").then(res => {
        this.roles = res.data
      })
    },
    home() {
      this.$router.push("/")
    },
    save() {
      this.request.post("/user", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失敗")
        }
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    handleEdit(row) {
      this.form = row
      this.dialogFormVisible = true
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val;
    },
    exp() {
      window.open("http://localhost:9090/user/export")
    },
    handleExcelImportSuccess() {
      this.$message.success("文件導(dǎo)入成功")
      this.load()
    },
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)  //[{}, {}, {}] => [1,2,3]
      this.request.post("/user/del/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success("刪除用戶成功")
          this.load()
        } else {
          this.$message.error("刪除用戶失敗")
        }
      })
    },
    reset() {
      this.username = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
  }
}
</script>
<style>
.headerBg {
  background: #eee!important;
}
</style>

?小結(jié)

以上就是對(duì)SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁(yè)查詢簡(jiǎn)單的概述,現(xiàn)在我們的項(xiàng)目就更加的趨于完美了,也提升了我們對(duì)于編程的能力和思維!

到此這篇關(guān)于SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁(yè)查詢功能的文章就介紹到這了,更多相關(guān)SpringBoot整合mybatis-plus分頁(yè)查詢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • MyEclipse到期破解代碼分享

    MyEclipse到期破解代碼分享

    前幾天有個(gè)小伙伴咨詢,使用的時(shí)候一直說(shuō)myeclipse已過(guò)期,需要購(gòu)買(mǎi),如何解決?可以去網(wǎng)上搜搜注冊(cè)碼,但作為程序猿這么做簡(jiǎn)直太無(wú)趣,看看我們自己來(lái)解決這個(gè)問(wèn)題
    2014-11-11
  • Java命名規(guī)則詳細(xì)總結(jié)

    Java命名規(guī)則詳細(xì)總結(jié)

    Class名應(yīng)是首字母大寫(xiě)的名詞。命名時(shí)應(yīng)該使其簡(jiǎn)潔而又具有描述性。異常類(lèi)的命名,應(yīng)以Exception結(jié)尾。Interface的命名規(guī)則與Class相同
    2013-10-10
  • Java HashMap兩種簡(jiǎn)便排序方法解析

    Java HashMap兩種簡(jiǎn)便排序方法解析

    這篇文章主要介紹了Java HashMap兩種簡(jiǎn)便排序方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • SpringBoot使用WebSocket實(shí)現(xiàn)向前端推送消息功能

    SpringBoot使用WebSocket實(shí)現(xiàn)向前端推送消息功能

    WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議,它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工(full-duplex)通信——允許服務(wù)器主動(dòng)發(fā)送信息給客戶端,本文給大家介紹了SpringBoot使用WebSocket實(shí)現(xiàn)向前端推送消息功能,需要的朋友可以參考下
    2024-05-05
  • SpringBoot自動(dòng)裝配原理詳細(xì)解析

    SpringBoot自動(dòng)裝配原理詳細(xì)解析

    這篇文章主要介紹了SpringBoot自動(dòng)裝配原理詳細(xì)解析,一個(gè)對(duì)象交給Spring來(lái)管理的三種方式 @Bean @Compoment @Import,
    @Bean主要在@Configuration中,通過(guò)方法進(jìn)行注入相關(guān)的Bean,@Compoent與@Service歸為一類(lèi),在類(lèi)上加注入對(duì)應(yīng)的類(lèi),需要的朋友可以參考下
    2024-01-01
  • 使用maven基本命令,打包包名問(wèn)題

    使用maven基本命令,打包包名問(wèn)題

    這篇文章主要介紹了使用maven基本命令,打包包名問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • 基于String實(shí)現(xiàn)同步鎖的方法步驟

    基于String實(shí)現(xiàn)同步鎖的方法步驟

    這篇文章主要給大家介紹了關(guān)于基于String實(shí)現(xiàn)同步鎖的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用String具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • maven打包時(shí)配置多環(huán)境參數(shù)的實(shí)現(xiàn)

    maven打包時(shí)配置多環(huán)境參數(shù)的實(shí)現(xiàn)

    本文主要介紹了maven打包時(shí)配置多環(huán)境參數(shù)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2025-04-04
  • Springboot內(nèi)外部logback多環(huán)境配置詳解

    Springboot內(nèi)外部logback多環(huán)境配置詳解

    本文主要介紹了Springboot內(nèi)外部logback多環(huán)境配置詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • 詳解通過(guò)maven運(yùn)行項(xiàng)目的兩種方式

    詳解通過(guò)maven運(yùn)行項(xiàng)目的兩種方式

    這篇文章主要介紹了通過(guò)maven運(yùn)行項(xiàng)目的兩種方式,給大家提到了通過(guò)tomcat的方式來(lái)啟動(dòng)maven項(xiàng)目的方法,通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2021-12-12

最新評(píng)論