SpringBoot基于MyBatis-Plus實(shí)現(xiàn)Lambda Query查詢的示例代碼
引言
MyBatis-Plus 是 MyBatis 的增強(qiáng)工具,簡(jiǎn)化了數(shù)據(jù)庫(kù)操作,并提高了開發(fā)效率。它提供了多種查詢方式,包括常規(guī)的 SQL 查詢、Lambda Query 查詢、分頁(yè)查詢、條件查詢等。在本篇博客中,我們將詳細(xì)講解如何使用 MyBatis-Plus 的各種查詢方式,涵蓋以下內(nèi)容:
- 基礎(chǔ)環(huán)境配置
- 表結(jié)構(gòu)設(shè)計(jì)
- 常見查詢方法
- 普通查詢
- Lambda 查詢
- 條件構(gòu)造器
- 聚合查詢
- 分頁(yè)查詢
- 復(fù)雜查詢與多表聯(lián)查
基礎(chǔ)環(huán)境配置
首先,你需要確保項(xiàng)目已經(jīng)引入了 MyBatis-Plus 相關(guān)的依賴。假設(shè)你的項(xiàng)目是基于 Spring Boot 的,下面是如何配置 Maven 依賴的示例。
依賴配置(Maven)
<dependencies> <!-- MyBatis-Plus Starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.0</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
application.yml 配置
spring: datasource: url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: # 配置 MyBatis-Plus mapper-locations: classpath:/mappers/*.xml typeAliasesPackage: com.example.demo.entity
表結(jié)構(gòu)設(shè)計(jì)
假設(shè)有以下兩個(gè)表:
- demo_student:學(xué)生信息
- demo_class:班級(jí)信息
demo_student 表結(jié)構(gòu)
CREATE TABLE demo_student ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, age INT, class_id INT, gender ENUM('M', 'F') DEFAULT 'M', FOREIGN KEY (class_id) REFERENCES demo_class(id) );
demo_student 表存儲(chǔ)學(xué)生信息,其中 class_id 是外鍵,指向 demo_class 表。
demo_class 表結(jié)構(gòu)
CREATE TABLE demo_class ( id INT AUTO_INCREMENT PRIMARY KEY, class_name VARCHAR(50) NOT NULL );
常見查詢方法
普通查詢(selectOne, selectList, selectById)
selectOne
:查詢單條記錄。selectList
:查詢多條記錄。selectById
:通過(guò)主鍵查詢一條記錄。
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DemoStudentService { @Autowired private DemoStudentMapper demoStudentMapper; // 查詢單個(gè)學(xué)生 public DemoStudent getStudentById(Long id) { return demoStudentMapper.selectById(id); } // 查詢所有學(xué)生 public List<DemoStudent> getAllStudents() { return demoStudentMapper.selectList(new QueryWrapper<>()); } }
Lambda Query 查詢(LambdaQueryWrapper)
MyBatis-Plus
提供了 LambdaQueryWrapper
,可以通過(guò) Lambda 表達(dá)式來(lái)避免字段名硬編碼。
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; public List<DemoStudent> getStudentsByAge(int age) { LambdaQueryWrapper<DemoStudent> queryWrapper = new LambdaQueryWrapper<>(); // 查詢年齡大于指定值的學(xué)生 queryWrapper.gt(DemoStudent::getAge, age); return demoStudentMapper.selectList(queryWrapper); }
條件構(gòu)造器(QueryWrapper)
QueryWrapper
允許通過(guò)構(gòu)建條件來(lái)查詢。它支持 eq、ne、lt、gt、like
等各種條件。
public List<DemoStudent> getStudentsByClassId(Long classId) { QueryWrapper<DemoStudent> queryWrapper = new QueryWrapper<>(); // 根據(jù)班級(jí)ID查詢 queryWrapper.eq("class_id", classId); return demoStudentMapper.selectList(queryWrapper); }
條件鏈?zhǔn)讲樵?/h3>
LambdaQueryWrapper
和QueryWrapper
支持鏈?zhǔn)秸{(diào)用,可以將多個(gè)條件組合成一個(gè)查詢。
public List<DemoStudent> getFemaleStudentsOver18() { LambdaQueryWrapper<DemoStudent> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(DemoStudent::getGender, "F") .gt(DemoStudent::getAge, 18); // 查找性別為女性,且年齡大于18歲的學(xué)生 return demoStudentMapper.selectList(queryWrapper); }
聚合查詢(selectCount, selectMax, selectMin 等)
MyBatis-Plus 支持基本的聚合查詢,比如統(tǒng)計(jì)、求最大值、最小值、平均值等。
// 查詢學(xué)生總數(shù) public int getTotalStudents() { return demoStudentMapper.selectCount(new QueryWrapper<>()); } // 查詢年齡最大值 public Integer getMaxAge() { return demoStudentMapper.selectMax(DemoStudent::getAge); } // 查詢年齡最小值 public Integer getMinAge() { return demoStudentMapper.selectMin(DemoStudent::getAge); }
分頁(yè)查詢
分頁(yè)查詢?cè)趯?shí)際開發(fā)中非常常見,MyBatis-Plus 提供了內(nèi)置的分頁(yè)功能,可以非常簡(jiǎn)單地實(shí)現(xiàn)。
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; public IPage<DemoStudent> getStudentsPage(int pageNum, int pageSize) { Page<DemoStudent> page = new Page<>(pageNum, pageSize); // 創(chuàng)建分頁(yè)對(duì)象 LambdaQueryWrapper<DemoStudent> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.gt(DemoStudent::getAge, 18); // 查詢年齡大于18的學(xué)生 return demoStudentMapper.selectPage(page, queryWrapper); // 返回分頁(yè)結(jié)果 }
分頁(yè)插件配置
分頁(yè)功能需要在 application.yml
中配置分頁(yè)插件:
mybatis-plus: global-config: db-config: id-type: auto configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl plugins: - com.baomidou.mybatisplus.extension.plugins.pagination.PageInterceptor
復(fù)雜查詢與多表聯(lián)查
在 MyBatis-Plus
中,雖然不直接支持JOIN
操作,但我們可以通過(guò)自定義 SQL 來(lái)實(shí)現(xiàn)復(fù)雜的聯(lián)表查詢。
示例:查詢學(xué)生和班級(jí)信息(聯(lián)查)
import org.apache.ibatis.annotations.Select; import java.util.List; public interface DemoStudentMapper { @Select("SELECT s.id AS student_id, s.name AS student_name, c.class_name " + "FROM demo_student s LEFT JOIN demo_class c ON s.class_id = c.id") List<StudentWithClass> selectStudentsWithClass(); }
實(shí)現(xiàn)自定義查詢與復(fù)雜查詢
對(duì)于一些需要自定義 SQL 的場(chǎng)景,可以直接使用 @Select 或 @Update 注解來(lái)編寫 SQL。
@Select("SELECT * FROM demo_student WHERE age > #{age} AND gender = #{gender}") List<DemoStudent> selectByAgeAndGender(int age, String gender);
總結(jié)
MyBatis-Plus
提供了極為豐富的查詢功能,通過(guò)簡(jiǎn)潔的 API 和靈活的查詢構(gòu)造器,可以非常方便地進(jìn)行數(shù)據(jù)庫(kù)查詢操作。通過(guò)以下幾點(diǎn),可以更好地理解和應(yīng)用 MyBatis-Plus 的查詢功能:
- 普通查詢:通過(guò)
selectOne, selectList, selectById
方法可以快速進(jìn)行數(shù)據(jù)查詢。 Lambda
查詢:通過(guò)LambdaQueryWrapper
構(gòu)建條件查詢,避免硬編碼字段名,提高代碼可維護(hù)性。- 條件構(gòu)造器:
QueryWrapper
和LambdaQueryWrapper
提供了多種條件構(gòu)建方式,支持鏈?zhǔn)秸{(diào)用。 - 分頁(yè)查詢:
MyBatis-Plus
提供了內(nèi)置的分頁(yè)支持,可以輕松進(jìn)行分頁(yè)查詢。 - 聚合查詢:支持常見的聚合操作,如
selectCount, selectMax, selectMin
等。 - 復(fù)雜查詢:通過(guò)自定義 SQL 支持聯(lián)表查詢,處理更復(fù)雜的查詢需求。
以上就是SpringBoot基于MyBatis-Plus實(shí)現(xiàn)Lambda Query查詢的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于MyBatis-Plus Lambda Query查詢的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java實(shí)現(xiàn)網(wǎng)絡(luò)文件下載以及下載到指定目錄
在Spring框架中,StreamUtils和FileCopyUtils兩個(gè)工具類提供了方便的文件下載功能,它們都屬于org.springframework.util包,可以通過(guò)簡(jiǎn)單的方法調(diào)用實(shí)現(xiàn)文件流的復(fù)制和下載,這些工具類支持多種參數(shù)傳遞,涵蓋了文件下載的多種場(chǎng)景2024-09-09解決RestTemplate第一次請(qǐng)求響應(yīng)速度較慢的問(wèn)題
這篇文章主要介紹了解決RestTemplate第一次請(qǐng)求響應(yīng)速度較慢的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10將ResultSet中得到的一行或多行結(jié)果集封裝成對(duì)象的實(shí)例
這篇文章主要介紹了將ResultSet中得到的一行或多行結(jié)果集封裝成對(duì)象的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05IDEA項(xiàng)目如何取消git版本管控并添加svn版本控制
在公司內(nèi)部服務(wù)器環(huán)境下,將代碼倉(cāng)庫(kù)從Gitee的Git遷移到SVN可以避免外部版本控制的風(fēng)險(xiǎn),遷移過(guò)程中,先刪除項(xiàng)目的.git文件夾,再通過(guò)Eclipse的設(shè)置界面刪除原Git配置并添加SVN配置,之后,將項(xiàng)目提交到SVN倉(cāng)庫(kù),確保使用ignore列表過(guò)濾不必要的文件2024-10-10詳解springboot項(xiàng)目啟動(dòng)時(shí)如何排除用不到的bean
使用springboot開發(fā)項(xiàng)目,我們有時(shí)候會(huì)排除一些項(xiàng)目里面用不到的bean,不然的話項(xiàng)目啟動(dòng)會(huì)報(bào)錯(cuò),這種情況通常是發(fā)生在什么場(chǎng)景里呢,以及如何解決呢,今天咱們就聊一聊2024-01-01Springboot 限制IP訪問(wèn)指定的網(wǎng)址實(shí)現(xiàn)
本文主要介紹了Springboot 限制IP訪問(wèn)指定的網(wǎng)址實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05java 實(shí)現(xiàn)回調(diào)代碼實(shí)例
本文主要介紹Java的回調(diào)機(jī)制,并附實(shí)例代碼以供大家參考學(xué)習(xí),有需要的小伙伴可以看下2016-07-07