> 技术文档 > 探索 MyBatis-Plus

探索 MyBatis-Plus


引言

在当今的 Java 开发领域,数据库操作是一个至关重要的环节。MyBatis 作为一款优秀的持久层框架,已经被广泛应用。而 MyBatis-Plus 则是在 MyBatis 基础上进行增强的工具,它简化了开发流程,提高了开发效率。本文将详细介绍 MyBatis-Plus 的使用,结合具体的代码示例,帮助你快速上手。

环境搭建

项目创建

首先,我们使用 Spring Boot 来创建一个基础项目。这里使用 Maven 作为项目管理工具,在 pom.xml 中添加必要的依赖:

 4.0.0 com.qcby Mybatis-plus 1.0-SNAPSHOT  org.springframework.boot spring-boot-starter-parent 2.7.4   1.8     org.springframework.boot spring-boot-starter   org.springframework.boot spring-boot-starter-test test   com.baomidou mybatis-plus-boot-starter 3.5.1    org.projectlombok lombok true   mysql mysql-connector-java runtime      org.springframework.boot spring-boot-maven-plugin   

配置数据源

在 application.yml 中配置数据库连接信息:

spring: # 配置数据源信息 datasource: # 配置数据源类型 type: com.zaxxer.hikari.HikariDataSource # 配置连接数据库信息 driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_plus username: root password: 123456mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

实体类定义

创建一个 User 实体类,使用 Lombok 注解简化代码

package com.qcby.entity;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableId;import lombok.Data;@Datapublic class User { @TableId(type = IdType.AUTO) private long id; private String name; private Integer age; private String email;}

Mapper 接口定义

定义一个 UserMapper 接口,继承 BaseMapper,MyBatis-Plus 会自动为我们提供基本的增删改查方法:

package com.qcby.mapper;import com.baomidou.mybatisplus.core.conditions.Wrapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.qcby.entity.User;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param;import java.io.Serializable;import java.util.Collection;import java.util.List;import java.util.Map;@Mapperpublic interface UserMapper extends BaseMapper { // 插入一条记录 int insert(User user); int deleteById(int id); int deleteById(User entity); int deleteByMap(@Param(\"columnMap\") Map columnMap); int delete(@Param(\"wrapper\") Wrapper queryWrapper); // 删除(根据 ID 批量删除) int deleteBatchIds(@Param(\"collection\") Collection idList); // 根据 ID 修改 int updateById(@Param(\"entity\") User user); int update(@Param(\"entity\") User user, @Param(\"wrapper\") Wrapper updateWrapper); // 查询(根据 ID 批量查询) List selectBatchIds(@Param(\"collection\") Collection idList); // 查询(根据 columnMap 条件) List selectByMap(@Param(\"columnMap\") Map columnMap); // 根据 entity 条件,查询一条记录 default User selectOne(@Param(\"wrapper\") Wrapper queryWrapper) { List ts = this.selectList(queryWrapper); if (ts != null && !ts.isEmpty()) { if (ts.size() != 1) { throw new RuntimeException(\"One record is expected, but the query result is multiple records\"); } return ts.get(0); } return null; } // 根据 Wrapper 条件,查询总记录数 Long selectCount(@Param(\"wrapper\") Wrapper queryWrapper); // 根据 entity 条件,查询全部记录 List selectList(@Param(\"wrapper\") Wrapper queryWrapper); // 根据 Wrapper 条件,查询全部记录 List<Map> selectMaps(@Param(\"wrapper\") Wrapper queryWrapper); // 根据 Wrapper 条件,查询全部记录(只返回第一个字段的值) List selectObjs(@Param(\"wrapper\") Wrapper queryWrapper); // 根据 entity 条件,查询全部记录(并翻页) <P extends IPage> P selectPage(P page, @Param(\"wrapper\") Wrapper queryWrapper);}

基本操作示例

插入数据

import com.qcby.entity.User;import com.qcby.mapper.UserMapper;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestpublic class MybatisPlusTest { @Autowired private UserMapper userMapper; @Test public void testInsert() { User user = new User(); user.setAge(18); user.setEmail(\"test@qcby.com\"); int insert = userMapper.insert(user); System.out.println(\"受影响行数:\" + insert); System.out.println(\"id 自动获取:\" + user.getId()); }}

 删除数据

@Testpublic void testDelete() { int delete = userMapper.deleteById(1948707997203062787L); System.out.println(delete);}

修改数据

@Testpublic void testUpdateById() { User user = new User(); user.setId(5); user.setName(\"test\"); user.setAge(18); user.setEmail(\"test@qcby.com\"); int update = userMapper.updateById(user); System.out.println(update);}

 查询数据

@Testpublic void testSelectList() { userMapper.selectList(null).forEach(System.out::println);}

分页查询

@Testpublic void testSelectPage() { // 设置分页参数,这里查询第 1 页,每页 10 条记录 Page page = new Page(1, 10); // 构建查询条件,这里查询年龄大于 16 的用户 QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.gt(\"age\", 16); // 调用 selectPage 方法进行分页查询 IPage userPage = userMapper.selectPage(page, queryWrapper); // 输出分页信息 System.out.println(\"当前页码: \" + userPage.getCurrent()); System.out.println(\"每页记录数: \" + userPage.getSize()); System.out.println(\"总记录数: \" + userPage.getTotal()); System.out.println(\"总页数: \" + userPage.getPages()); // 输出查询结果 userPage.getRecords().forEach(System.out::println);}

总结

通过以上的介绍和示例代码,我们可以看到 MyBatis-Plus 极大地简化了数据库操作的开发流程。它提供了丰富的方法和强大的条件构造器,让我们可以更高效地完成增删改查操作。无论是小型项目还是大型项目,MyBatis-Plus 都是一个值得选择的持久层框架。希望本文能帮助你快速掌握 MyBatis-Plus 的使用,在实际开发中发挥出它的优势。