一、简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
mybatis-plus能够简化开发,提高效率
这个蓝色的胖鸟就是plus啦~
Mybatis支持很多数据库如常用的mysql, oracle, DB2, H2, HSQL, SQLite,PostgreSQL,SQLServer等等
框架架构
1.1 快速入门
建立数据库插入内容进行测试
我们就用官网上的例子来测试
内容如下:
1.1.1 添加依赖
我们创建SpringBoot工程,导入相关依赖
mybatis-plus-boot-starter <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.pyy.mp</groupId> <artifactId>mp</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mp</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
1.1.2 配置
编写mysql数据源信息
spring: datasource: username: root password: root url: jdbc:mysql://localhost:3306/mp driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
编写实体类
package com.pyy.mp.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }
编写Mapper接口继承BaseMapper
@Repository和@Controller、@Service、@Component的作用差不多,都是把对象交给spring管理。 @Repository用在持久层的接口上,这个注解是将接口的一个实现类交给spring管理。 package com.pyy.mp.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.pyy.mp.pojo.User; import org.springframework.stereotype.Repository; @Repository public interface UserMapper extends BaseMapper<User> { }
在SpringBoot启动类中添加MapperScan注解扫描Mapper类
package com.pyy.mp; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan("com.pyy.mp") @SpringBootApplication public class MpApplication { public static void main(String[] args) { SpringApplication.run(MpApplication.class, args); } }
1.1.3 测试
语法糖:用简介的写法表达逻辑
成语:用简介的词语表示句意
package com.pyy.mp; import com.pyy.mp.mapper.UserMapper; import com.pyy.mp.pojo.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Arrays; import java.util.List; @SpringBootTest class MpApplicationTests { // 继承了BaseMapper,所有的方法都来自自己的父类 @Autowired private UserMapper userMapper; @Test void contextLoads() { // 参数是一个weapper,条件构造器,这里我们先不用。写成null List<User> users = userMapper.selectList(null); // ::的写法 // users.forEach(System.out::println); // 循环的写法 // for (User user : users) { // System.out.println(user); // } // lambda表达式的写法 users.forEach(a->{ System.out.println(a); }); } }
结果如下
入门结束,可以看出Mybatis-plus真的很简单,连映射文件sql语句都不用写,只需要引入 starter 工程,并配置 mapper 扫描路径即可
二、核心功能
2.1 通用CRUD
我们通过继承BaseMapper就可以获取到通用的CRUD操作
2.1.1 插入操作
插入操作很简单,做好数据库字段与实体类属性的对应
之后调用通用CRUD中的插入操作
数据库字段如下:
实体类如下:
@Data @AllArgsConstructor @NoArgsConstructor public class User { @TableId(type = IdType.INPUT) private Long id; private String name; private Integer age; private String email; }
测试
@SpringBootTest class MpApplicationTests { // 继承了BaseMapper,所有的方法都来自自己的父类 @Autowired private UserMapper userMapper; @Test public void testInsert(){ User pyy = new User(); pyy.setId(6L); pyy.setName("A"); pyy.setAge(3); pyy.setEmail("A@qq.cn"); int result = userMapper.insert(pyy); System.out.println(result); System.out.println(pyy); }
结果如下:
Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6ed16657] was not registered for synchronization because synchronization is not active JDBC Connection [HikariProxyConnection@1942612200 wrapping com.mysql.cj.jdbc.ConnectionImpl@de8039f] will not be managed by Spring ==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? ) ==> Parameters: 6(Long), A(String), 3(Integer), A@qq.cn(String) <== Updates: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6ed16657] 1 User(id=6, name=A, age=3, email=A@qq.cn)
@TableField
@TableField注解可以指定字段的一些属性,能解决的问题有两个:
对象中的属性名和字段名不一致问题(非驼峰)
对象中属性字段在表中不存在
属性 类型 必须指定 默认值 描述
value String 否 “” 数据库字段名
exist boolean 否 true 是否为数据库表字段
select boolean 否 true 是否进行 select 查询
测试
实体类
package com.pyy.mp.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @TableName("user")//表名注解,标识实体类对应的表 public class User { @TableId(type = IdType.INPUT) private Long id; private String name; @TableField(value = "age") private Integer aage; @TableField(select = false)//select不查询这个字段 private String email; @TableField(exist = false) private String noexist; } 测试类 @SpringBootTest class MpApplicationTests { // 继承了BaseMapper,所有的方法都来自自己的父类 @Autowired private UserMapper userMapper; @Test void contextLoads() { // 参数是一个weapper,条件构造器,这里我们先不用。写成null List<User> users = userMapper.selectList(null); // ::的写法 // users.forEach(System.out::println); // 循环的写法 // for (User user : users) { // System.out.println(user); // } // lambda表达式的写法 users.forEach(a->{ System.out.println(a); }); } 测试结果 Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7979b8b7] was not registered for synchronization because synchronization is not active JDBC Connection [HikariProxyConnection@1766122814 wrapping com.mysql.cj.jdbc.ConnectionImpl@52e04737] will not be managed by Spring ==> Preparing: SELECT id,name,age AS aage FROM user ==> Parameters: <== Columns: id, name, aage <== Row: 1, Jone, 18 <== Row: 2, Jack, 20 <== Row: 3, Tom, 28 <== Row: 4, Sandy, 21 <== Row: 5, Billie, 24 <== Row: 6, A, 3 <== Total: 6 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7979b8b7] User(id=1, name=Jone, aage=18, email=null, noexist=null) User(id=2, name=Jack, aage=20, email=null, noexist=null) User(id=3, name=Tom, aage=28, email=null, noexist=null) User(id=4, name=Sandy, aage=21, email=null, noexist=null) User(id=5, name=Billie, aage=24, email=null, noexist=null) User(id=6, name=A, aage=3, email=null, noexist=null)
2.1.2 更新操作
在MP中更新有两种方式,一种是根据id更新,一种是根据条件更新
QueryWrapper:
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件
--------------------------------------------------------------------------分割线--------------------------------------------------------------
UpdateWrapper
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件及 LambdaUpdateWrapper, 可以通过 new UpdateWrapper().lambda() 方法获取!
根据id更新
@Test public void testUpdate1() { User user = new User(); //更新的字段 user.setId(6L); user.setAge(14); user.setName("DDD"); int i = userMapper.updateById(user); System.out.println(i); } Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5e65afb6] was not registered for synchronization because synchronization is not active JDBC Connection [HikariProxyConnection@1012776440 wrapping com.mysql.cj.jdbc.ConnectionImpl@352c44a8] will not be managed by Spring ==> Preparing: UPDATE user SET name=?, age=? WHERE id=? ==> Parameters: DDD(String), 14(Integer), 6(Long) <== Updates: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5e65afb6]
根据条件更新
package com.pyy.mp.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { @TableId(type = IdType.INPUT) private Long id; private String name; private Integer age; private String email; } 根绝QueryWrapper进行更新 @SpringBootTest class MpApplicationTests { // 继承了BaseMapper,所有的方法都来自自己的父类 @Autowired private UserMapper userMapper; @Test public void testUpdate(){ User user = new User(); //更新的字段 user.setAge(14); user.setName("CCC"); // 更新的条件 QueryWrapper<User> wrapper = new QueryWrapper<>(); // 更新的条件是id = 6 wrapper.eq("id",6); int i = userMapper.update(user,wrapper); System.out.println(i); } } Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@65a48602] was not registered for synchronization because synchronization is not active JDBC Connection [HikariProxyConnection@1706939736 wrapping com.mysql.cj.jdbc.ConnectionImpl@1dba4e06] will not be managed by Spring ==> Preparing: UPDATE user SET name=?, age=? WHERE id = ? ==> Parameters: CCC(String), 14(Integer), 6(Integer) <== Updates: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@65a48602] 1 我们还可以根据updateWrapper进行更新 @Test public void testUpdate02(){ UpdateWrapper<User> wrapper01 = new UpdateWrapper<>(); wrapper01.eq("id",6).set("name","sadas"); int i = userMapper.update(null,wrapper01); System.out.println(i); } Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@28da7d11] was not registered for synchronization because synchronization is not active JDBC Connection [HikariProxyConnection@728236551 wrapping com.mysql.cj.jdbc.ConnectionImpl@2a3194c6] will not be managed by Spring ==> Preparing: UPDATE user SET name=? WHERE id = ? ==> Parameters: sadas(String), 14(Integer), 6(Integer) <== Updates: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@28da7d11] 1