欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

一、前言

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

二、手動實現(xiàn)分頁查詢

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

SELECT * FROM map limit 1,2;

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

那么在Springboot中該如何寫呢?

三、了解@RequestParam

1.什么是@RequestParam

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

 2.語法

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

value:參數(shù)名

required:是否包含該參數(shù),默認為true,表示該請求路徑中必須包含該參數(shù),如果不包含就報錯。

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

3.測試環(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會自動指定)--視圖解析器
4、創(chuàng)建 業(yè)務(wù)處理器 Controller類
5、測試

四、了解QueryWrapper

1.QueryWrapper是什么?

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

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

1、單表操作

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

@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);
}

以上代碼對應的sql為:

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

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

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

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實現(xiàn)分頁查詢

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ù)錯誤");
        }
        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ù)錯誤");
        }
        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ù)錯誤");
        }
        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里面寫好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ù)庫的id進行查詢出數(shù)據(jù)庫的數(shù)據(jù)

queryWrapper.orderByDesc("id")

六、了解equals

1.什么是equals

        equals():equals是Object中的方法,用于檢測一個對象是否等于另一個對象,在Object中equals方法實際"ruturn (this==obj)",用到的還是"==",說明如果對象不重寫equals方法,實際該對象的equals和"=="作用是一樣的,都是比較的地址值(因為"=="比較的就是地址值),但是大部分類都會重寫父類的equals方法,用來檢測兩個對象是否相等,即兩個對象的內(nèi)容是否相等,例如String就重寫了equals方法,用來比較兩個字符串內(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來確定我們查詢數(shù)據(jù)的對象,所以我們這里選擇使用username來查詢數(shù)據(jù)庫里面的具體數(shù)據(jù)

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

七、前端使用

1.前端技術(shù)棧

        對于前端,我們使用的是Vue+Element來進行功能實現(xiàn),對于跨域的處理我使用的是axios進行處理,并且對axios進行了封裝,具體步驟請查看:解決SpringBoot和前端Vue的跨域問題

2.組件使用

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

我們進行組件使用,并且設(shè)置分頁的數(shù)據(jù)數(shù)量,數(shù)據(jù)可分為一頁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ù)渲染

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

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

 最后進行數(shù)據(jù)請求,請求后臺寫好的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="請輸入用戶名" 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='確認'
          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>導入</el-button>
      </el-upload>
      <el-button type="primary" class="ml-5" @click="exp"><i class="el-icon-download" />導出</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("文件導入成功")
      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é)

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

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

相關(guān)文章

  • springboot搭建訪客管理系統(tǒng)的實現(xiàn)示例

    springboot搭建訪客管理系統(tǒng)的實現(xiàn)示例

    這篇文章主要介紹了springboot搭建訪客管理系統(tǒng)的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • java通過url讀取遠程數(shù)據(jù)并保持到本地的實例代碼

    java通過url讀取遠程數(shù)據(jù)并保持到本地的實例代碼

    本文通過實例代碼給大家介紹了java通過url讀取遠程數(shù)據(jù)并保持到本地的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-07-07
  • 詳解Java動態(tài)加載數(shù)據(jù)庫驅(qū)動

    詳解Java動態(tài)加載數(shù)據(jù)庫驅(qū)動

    本篇文章主要介紹了詳解Java動態(tài)加載數(shù)據(jù)庫驅(qū)動,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • SpringBoot執(zhí)行有返回值的異步任務(wù)問題

    SpringBoot執(zhí)行有返回值的異步任務(wù)問題

    這篇文章主要介紹了SpringBoot執(zhí)行有返回值的異步任務(wù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • 解決JMap抓取heap使用統(tǒng)計信息報錯的問題

    解決JMap抓取heap使用統(tǒng)計信息報錯的問題

    這篇文章主要介紹了解決JMap抓取heap使用統(tǒng)計信息報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 詳解Springboot下載Excel的三種方式

    詳解Springboot下載Excel的三種方式

    本文給大家分享Springboot下載Excel三種方式,主要分為瀏覽器下載和代碼本地下載實現(xiàn)的方式,針對每種實現(xiàn)方式給大家介紹的非常詳細,需要的朋友參考下吧
    2021-07-07
  • SpringCloud開發(fā)課程查詢功能

    SpringCloud開發(fā)課程查詢功能

    這篇文章主要介紹了SpringCloud開發(fā)課程查詢功能,本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • SpringBoot3整合mybatis-plus的實現(xiàn)

    SpringBoot3整合mybatis-plus的實現(xiàn)

    MyBatis-Plus是一個MyBatis的增強工具,在MyBatis的基礎(chǔ)上只做增強不做改變,本文主要介紹了Mybatis-Plus3.x的具體使用,具有一定的參考價值,感興趣的可以了解一下
    2023-10-10
  • 解決springboot 無法配置多個靜態(tài)路徑的問題

    解決springboot 無法配置多個靜態(tài)路徑的問題

    這篇文章主要介紹了解決springboot 無法配置多個靜態(tài)路徑的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java實現(xiàn)動態(tài)數(shù)字時鐘

    Java實現(xiàn)動態(tài)數(shù)字時鐘

    這篇文章主要為大家詳細介紹了Java實現(xiàn)動態(tài)數(shù)字時鐘,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-12-12

最新評論