马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
关注:CodingTechWork
弁言
MyBatis-Plus 是 MyBatis 的增强工具,简化了数据库使用,并进步了开辟服从。它提供了多种查询方式,包罗通例的 SQL 查询、Lambda Query 查询、分页查询、条件查询等。在本篇博客中,我们将详细解说怎样使用 MyBatis-Plus 的各种查询方式,涵盖以下内容:
- 根本环境设置
- 表布局计划
- 常见查询方法
- 平凡查询
- Lambda 查询
- 条件构造器
- 聚合查询
- 分页查询
- 复杂查询与多表联查
根本环境设置
起首,你须要确保项目已经引入了 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:门生信息
- demo_class:班级信息
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)
- 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 的查询功能:
- 平凡查询:通过selectOne, selectList, selectById方法可以快速举行数据查询。
- Lambda查询:通过LambdaQueryWrapper构建条件查询,制止硬编码字段名,进步代码可维护性。
- 条件构造器:QueryWrapper和LambdaQueryWrapper提供了多种条件构建方式,支持链式调用。
- 分页查询:MyBatis-Plus提供了内置的分页支持,可以轻松举行分页查询。
- 聚合查询:支持常见的聚合使用,如selectCount, selectMax, selectMin等。
- 复杂查询:通过自界说 SQL 支持联表查询,处置惩罚更复杂的查询需求。
|