探索 MyBatis-Plus
引言
在当今的 Java 开发领域,数据库操作是一个至关重要的环节。MyBatis 作为一款优秀的持久层框架,已经被广泛应用。而 MyBatis-Plus 则是在 MyBatis 基础上进行增强的工具,它简化了开发流程,提高了开发效率。本文将详细介绍 MyBatis-Plus 的使用,结合具体的代码示例,帮助你快速上手。
环境搭建
项目创建
首先,我们使用 Spring Boot 来创建一个基础项目。这里使用 Maven 作为项目管理工具,在 pom.xml 中添加必要的依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.qcby</groupId><artifactId>Mybatis-plus</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.4</version></parent><properties><java.version>1.8</java.version> <!-- 或更高版本 --></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version></dependency><!-- 注解替代 get/set 方法 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
配置数据源
在 application.yml 中配置数据库连接信息:
spring:# 配置数据源信息datasource:# 配置数据源类型type: com.zaxxer.hikari.HikariDataSource# 配置连接数据库信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plususername: rootpassword: 123456
mybatis-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;@Data
public class User {@TableId(type = IdType.AUTO)private long id;private String name;private Integer age;private String email;
}
Mapper 接口定义
定义一个 UserMapper
接口,继承 BaseMapper<User>
,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;@Mapper
public interface UserMapper extends BaseMapper<User> {// 插入一条记录int insert(User user);int deleteById(int id);int deleteById(User entity);int deleteByMap(@Param("columnMap") Map<String, Object> columnMap);int delete(@Param("wrapper") Wrapper<User> queryWrapper);// 删除(根据 ID 批量删除)int deleteBatchIds(@Param("collection") Collection<?> idList);// 根据 ID 修改int updateById(@Param("entity") User user);int update(@Param("entity") User user, @Param("wrapper") Wrapper<User> updateWrapper);// 查询(根据 ID 批量查询)List<User> selectBatchIds(@Param("collection") Collection<? extends Serializable> idList);// 查询(根据 columnMap 条件)List<User> selectByMap(@Param("columnMap") Map<String, Object> columnMap);// 根据 entity 条件,查询一条记录default User selectOne(@Param("wrapper") Wrapper<User> queryWrapper) {List<User> 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<User> queryWrapper);// 根据 entity 条件,查询全部记录List<User> selectList(@Param("wrapper") Wrapper<User> queryWrapper);// 根据 Wrapper 条件,查询全部记录List<Map<String, Object>> selectMaps(@Param("wrapper") Wrapper<User> queryWrapper);// 根据 Wrapper 条件,查询全部记录(只返回第一个字段的值)List<Object> selectObjs(@Param("wrapper") Wrapper<User> queryWrapper);// 根据 entity 条件,查询全部记录(并翻页)<P extends IPage<User>> P selectPage(P page, @Param("wrapper") Wrapper<User> 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;@SpringBootTest
public class MybatisPlusTest {@Autowiredprivate UserMapper userMapper;@Testpublic 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());}
}
删除数据
@Test
public void testDelete() {int delete = userMapper.deleteById(1948707997203062787L);System.out.println(delete);
}
修改数据
@Test
public 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);
}
查询数据
@Test
public void testSelectList() {userMapper.selectList(null).forEach(System.out::println);
}
分页查询
@Test
public void testSelectPage() {// 设置分页参数,这里查询第 1 页,每页 10 条记录Page<User> page = new Page<>(1, 10);// 构建查询条件,这里查询年龄大于 16 的用户QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age", 16);// 调用 selectPage 方法进行分页查询IPage<User> 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 的使用,在实际开发中发挥出它的优势。