一、前言
? ? ? ? 最近學(xué)習(xí)了SpringBoot分頁(yè)查詢(xún)的兩種寫(xiě)法,一種是手動(dòng)實(shí)現(xiàn),另一種是使用框架實(shí)現(xiàn)?,F(xiàn)在我將具體的實(shí)現(xiàn)流程分享一下。
二、手動(dòng)實(shí)現(xiàn)分頁(yè)查詢(xún)
????????先復(fù)習(xí)一下,SQL中的limit關(guān)鍵字,下面一行sql語(yǔ)句的意思是從第二個(gè)數(shù)據(jù)開(kāi)始查,查詢(xún)出兩條數(shù)據(jù)
SELECT * FROM map limit 1,2;
????????使用limit前一個(gè)參數(shù)pageNum是從第幾個(gè)數(shù)據(jù)開(kāi)始查,后一個(gè)參數(shù)pageSize是查詢(xún)多少條數(shù)據(jù),注意數(shù)據(jù)庫(kù)查詢(xún)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工程、引入依賴(lài)
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、單表操作
代碼如下(示例):我要查詢(xún)姓名、班級(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è)放查詢(xún)條件的盒子,我們把查詢(xún)條件放在里面,他就會(huì)自動(dòng)按照對(duì)應(yīng)的條件進(jìn)行查詢(xún)數(shù)據(jù)。
????????根據(jù)不同的查詢(xún)要求,有不同的用法,常用到的比如: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è)查詢(xú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ù)錯(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)行查詢(xú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)?=="比較的就是地址值),但是大部分類(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)確定我們查詢(xún)數(shù)據(jù)的對(duì)象,所以我們這里選擇使用username來(lái)查詢(xún)數(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)題_慕言要努力的博客-CSDN博客
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)查詢(xú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)輸入用戶(hù)名" 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="用戶(hù)名" ></el-table-column>
<el-table-column prop="nickname" label="昵稱(chēng)" ></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="用戶(hù)信息" :visible.sync="dialogFormVisible" width="30%">
<el-form :model="form" label-width="100px" size="small">
<el-form-item label="用戶(hù)名" >
<el-input v-model="form.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="昵稱(chēng)" >
<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("刪除用戶(hù)成功")
this.load()
} else {
this.$message.error("刪除用戶(hù)失敗")
}
})
},
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è)查詢(xún)簡(jiǎn)單的概述,現(xiàn)在我們的項(xiàng)目就更加的趨于完美了,也提升了我們對(duì)于編程的能力和思維!文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-792954.html
????????如果這篇文章有幫助到你,希望可以給作者點(diǎn)個(gè)贊??,創(chuàng)作不易,如果有對(duì)后端技術(shù)、前端領(lǐng)域感興趣的,也歡迎關(guān)注 ,我將會(huì)給你帶來(lái)巨大的收獲與驚喜??????!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-792954.html
到了這里,關(guān)于SpringBoot整合mybatis-plus實(shí)現(xiàn)分頁(yè)查詢(xún)(建議收藏)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!