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

SpringBoot基于MyBatis-Plus實(shí)現(xiàn)Lambda Query查詢的示例代碼

 更新時(shí)間:2025年01月12日 08:41:41   作者:Andya  
MyBatis-Plus 是 MyBatis 的增強(qiáng)工具,簡(jiǎn)化了數(shù)據(jù)庫(kù)操作,并提高了開發(fā)效率,它提供了多種查詢方式,包括常規(guī)的 SQL 查詢、Lambda Query 查詢、分頁(yè)查詢、條件查詢等,在本篇博客中,我們將詳細(xì)講解如何使用 MyBatis-Plus 的各種查詢方式,需要的朋友可以參考下

引言

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)造器:QueryWrapperLambdaQueryWrapper提供了多種條件構(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)文章

最新評(píng)論