java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > MyBatis-Plus Lambda Query查询

SpringBoot基于MyBatis-Plus实现Lambda Query查询的示例代码

作者:Andya

MyBatis-Plus 是 MyBatis 的增强工具,简化了数据库操作,并提高了开发效率,它提供了多种查询方式,包括常规的 SQL 查询、Lambda Query 查询、分页查询、条件查询等,在本篇博客中,我们将详细讲解如何使用 MyBatis-Plus 的各种查询方式,需要的朋友可以参考下

引言

MyBatis-Plus 是 MyBatis 的增强工具,简化了数据库操作,并提高了开发效率。它提供了多种查询方式,包括常规的 SQL 查询、Lambda Query 查询、分页查询、条件查询等。在本篇博客中,我们将详细讲解如何使用 MyBatis-Plus 的各种查询方式,涵盖以下内容:

基础环境配置

首先,你需要确保项目已经引入了 MyBatis-Plus 相关的依赖。假设你的项目是基于 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

表结构设计

假设有以下两个表:

demo_student 表结构

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 表存储学生信息,其中 class_id 是外键,指向 demo_class 表。

demo_class 表结构

CREATE TABLE demo_class (
  id INT AUTO_INCREMENT PRIMARY KEY,
  class_name VARCHAR(50) NOT NULL
);

常见查询方法

普通查询(selectOne, selectList, selectById)

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;

    // 查询单个学生
    public DemoStudent getStudentById(Long id) {
        return demoStudentMapper.selectById(id);
    }

    // 查询所有学生
    public List<DemoStudent> getAllStudents() {
        return demoStudentMapper.selectList(new QueryWrapper<>());
    }
}

Lambda Query 查询(LambdaQueryWrapper)

MyBatis-Plus 提供了 LambdaQueryWrapper,可以通过 Lambda 表达式来避免字段名硬编码。

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

public List<DemoStudent> getStudentsByAge(int age) {
    LambdaQueryWrapper<DemoStudent> queryWrapper = new LambdaQueryWrapper<>();
    // 查询年龄大于指定值的学生
    queryWrapper.gt(DemoStudent::getAge, age);  
    return demoStudentMapper.selectList(queryWrapper);
}

条件构造器(QueryWrapper)

QueryWrapper 允许通过构建条件来查询。它支持 eq、ne、lt、gt、like 等各种条件。

public List<DemoStudent> getStudentsByClassId(Long classId) {
    QueryWrapper<DemoStudent> queryWrapper = new QueryWrapper<>();
    // 根据班级ID查询
    queryWrapper.eq("class_id", classId);  
    return demoStudentMapper.selectList(queryWrapper);
}

条件链式查询

LambdaQueryWrapper 和QueryWrapper支持链式调用,可以将多个条件组合成一个查询。

public List<DemoStudent> getFemaleStudentsOver18() {
    LambdaQueryWrapper<DemoStudent> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(DemoStudent::getGender, "F")
                .gt(DemoStudent::getAge, 18);  // 查找性别为女性,且年龄大于18岁的学生
    return demoStudentMapper.selectList(queryWrapper);
}

聚合查询(selectCount, selectMax, selectMin 等)

MyBatis-Plus 支持基本的聚合查询,比如统计、求最大值、最小值、平均值等。

// 查询学生总数
public int getTotalStudents() {
    return demoStudentMapper.selectCount(new QueryWrapper<>());
}

// 查询年龄最大值
public Integer getMaxAge() {
    return demoStudentMapper.selectMax(DemoStudent::getAge);
}

// 查询年龄最小值
public Integer getMinAge() {
    return demoStudentMapper.selectMin(DemoStudent::getAge);
}

分页查询

分页查询在实际开发中非常常见,MyBatis-Plus 提供了内置的分页功能,可以非常简单地实现。

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);  // 创建分页对象
    LambdaQueryWrapper<DemoStudent> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.gt(DemoStudent::getAge, 18);  // 查询年龄大于18的学生
    return demoStudentMapper.selectPage(page, queryWrapper);  // 返回分页结果
}

分页插件配置

分页功能需要在 application.yml 中配置分页插件:

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

复杂查询与多表联查

在 MyBatis-Plus中,虽然不直接支持JOIN操作,但我们可以通过自定义 SQL 来实现复杂的联表查询。
示例:查询学生和班级信息(联查)

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

实现自定义查询与复杂查询

对于一些需要自定义 SQL 的场景,可以直接使用 @Select 或 @Update 注解来编写 SQL。

@Select("SELECT * FROM demo_student WHERE age > #{age} AND gender = #{gender}")
List<DemoStudent> selectByAgeAndGender(int age, String gender);

总结

MyBatis-Plus提供了极为丰富的查询功能,通过简洁的 API 和灵活的查询构造器,可以非常方便地进行数据库查询操作。通过以下几点,可以更好地理解和应用 MyBatis-Plus 的查询功能:

以上就是SpringBoot基于MyBatis-Plus实现Lambda Query查询的示例代码的详细内容,更多关于MyBatis-Plus Lambda Query查询的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文