補充:按條件查詢有兩種方式:
方式1:直接用SQL語句(個人覺得就用這種方式)。例如前面的按編号查詢使用者
方式2:Mybatisplus自帶的方法。
https://baomidou.com/pages/10c804/
AbstractWrapper父類下的QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper)方法。
其中,QueryWrapper用于查詢,UpdateWrapper用于更新。
官方網站提供了各種方法。僅用于單表查詢,這樣會比較快。
分頁查詢
Mybatisplus提供了分頁插件。需要編寫配置檔案,先建一個config檔案夾,以後所有配置放在該檔案夾下。再建立一個配置類MyBatisPlusConfig。
代碼如下:
package com.example.mpdemo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor PaginationInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//定義了一個分頁攔截器
PaginationInnerInterceptor PaginationgInterceptoe = new PaginationInnerInterceptor(DbType.MYSQL);
interceptor.addInnerInterceptor(PaginationgInterceptoe);
return interceptor;
}
}
測試:利用提供的selectpage來按頁進行查處,而不是查詢所有資料。
//分頁查詢
@GetMapping("/user/findByPage")
public IPage findByPage(){
//設定啟始值及每頁條數
Page<User> page = new Page<>(0,2);
IPage iPage = userMapper.selectPage(page,QueryWrapper:null);
return iPage;
}
這裡注意幾個參數,Page<User>是從User表中取資料。Page<>(0,2)是設定從第0條開始,取兩條。
IPage iPage = userMapper.selectPage(page,QueryWrapper:null);
IPage是分頁對象。這裡是描述結果集的,所有查詢出的結果都封裝到iPage。後面還可以用QueryWrapper方法設定條件。
運作浏覽器: http://localhost:8080/user/findByPage
這裡看得不是很清楚,可以在google浏覽器中右鍵點檢查,在右側的選項中選NetWork,然後重新整理網頁。
分為2頁,查詢有兩條資料,總共同三條資料。
注意:這裡用Mybatisplus方法,要将實體user類在資料庫中不存在的orders屬性,标注@TableField(exist = false),否則會報錯。