一、简介
1、特点
MyBatis 是一个半自动的 ORM 框架。MyBatis-Plus(简称 MP)是MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。【提示】本文使用的版本是3.1.1
2、特性
1)无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑;
2)损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作;
3)强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求;
4)支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错;
5)支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、QLServer 等多种数据库;
6)支持主键自动生成:支持多达4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题;
7)支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动,但最新版已经移除了;
8)支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作。ActiveRecord 主要是一种数据访问设计模式,可以实现数据对象到关系数据库的映射。
9)支持自定义全局通用操作:支持全局通用方法注入,Write once, use anywhere ;
10)支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词;
11)内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用;
12)内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询;
13)内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询;
14)内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作;
15)内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击;
二、框架结构
三、基本开发环境
- 基于 Java 开发,建议 jdk 1.8+ 版本。
- 需要使用到 Spring Boot
- 需要使用到 Maven
- 需要使用 MySQL
1. 准备数据
- 我们需要准备一张 user 表
DROP TABLE IF EXISTS t_user;
CREATE TABLE t_user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
- 然后给t_user 表中添加一些数据
DELETE FROM t_user;
INSERT INTO t_user (id, name, age, email) VALUES
(1, '张三', 13, 'zhangsan@qq.com'),
(2, '李四', 14, 'lisi@qq.com'),
(3, '王五', 15, 'wangwu@qq.com'),
(4, '赵六', 16, 'zhaoliu@qq.com'),
(5, '阿钟小哥', 18, 'azhongxiaoge@qq.com');
2. Hello World
我们的目的:通过几个简单的步骤,我们就实现了 t_user 表的 CRUD 功能,甚至连 XML 文件都不用编写!
第一步:创建一个 Spring Boot 项目
推荐,登录 https://start.spring.io 构建并下载一个干净的 Spring Boot 工程。
第二步:编辑 pom.xml 文件添加相关的依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
【注意】引入 MyBatis-Plus
之后请不要再次引入 MyBatis
以及 MyBatis-Spring
,以避免因版本差异导致的问题。
【如果是 SpringMVC 项目】
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.1.1</version>
</dependency>
第三步:配置 application.yml 文件
编辑 application.yml 配置文件,主要是添加 druid 数据库的相关配置:
# DataSource Config
spring:
datasource:
# 此处使用 druid 数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
在 Spring Boot 启动类中添加 @MapperScan
注解,用于扫描 Mapper 文件夹:
@SpringBootApplication
@MapperScan("com.learn.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(QuickStartApplication.class, args);
}
}
【注意】如果是 SpringMVC 项目,需要在 <bean>
标签中配置 MapperScan。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.learn.mapper"/>
</bean>
然后还可以调整 SqlSessionFactory 为 Mybatis-Plus 的 SqlSessionFactory。
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
第四步:创建对应的类
新建 User 类:
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
【注意】@Data 是 Lombok 提供的能让代码更加简洁的注解,能够减少大量的模板代码。注解在类上,为类提供读写属性,此外还提供了 equals()、hashCode()、toString() 方法。
如果在 Eclipse 中使用,需要我们手动安装,具体请参考 https://www.projectlombok.org/setup/eclipse
【参考:Lombok 常用注解】
@NonNull : 注解在参数上, 如果该类参数为 null , 就会报出异常, throw new NullPointException(参数名)
@Cleanup : 注释在引用变量前, 自动回收资源 默认调用 close() 方法
@Getter/@Setter : 注解在类上, 为类提供读写属性
@Getter(lazy=true) :
@ToString : 注解在类上, 为类提供 toString() 方法
@EqualsAndHashCode : 注解在类上, 为类提供 equals() 和 hashCode() 方法
@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor : 注解在类上, 为类提供无参,有指定必须参数, 全参构造函数
@Data : 注解在类上, 为类提供读写属性, 此外还提供了 equals()、hashCode()、toString() 方法
@Value :
@Builder : 注解在类上, 为类提供一个内部的 Builder
@SneakThrows :
@Synchronized : 注解在方法上, 为方法提供同步锁
@Log :
@Log4j : 注解在类上, 为类提供一个属性名为 log 的 log4j 的日志对象
@Slf4j : 注解在类上, 为类提供一个属性名为 log 的 log4j 的日志对象
新建 UserMapper 映射接口类:
public interface UserMapper extends BaseMapper<User> {
}
第五步:愉快地测试
新建 Test 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class myTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect(){
// 此处 null 指的是不用根据参数去查询
// 可以调用 CRUD 相关的多种方式
// 1. 查询所有的数据
List<User> userList = userMapper.selectList(null);
userList.forEach(user -> System.out.println(user.getName()));
// 2. 根据 id 删除
userMapper.deleteById(1);
// 3. 添加数据
User user = new User();
user.setName("阿钟");
user.setEmail("azhong@qq.com");
user.setAge(18);
userMapper.insert(user);
// 4. 更新数据
user.setId(1);
user.setName("阿钟小哥");
user.setEmail("azhongxiaoge@qq.com");
userMapper.updateById(user);
}
}
四、常见注解
- @TableName:表名描述
- @TableId:主键注释
- @TableField:字段注解(非主键)
- @Version:乐观锁注解,主要用于标注在字段上
- @EnumValue:通枚举类注解(注解在枚举字段上)
- @TableLogic:表字段逻辑处理注解(逻辑删除)
- @SqlParser:租户注解(支持注解在 mapper 上)
- @KeySequence:序列主键策略,属性有:value、resultMap
案例:多表联查
1. 准备数据
User 用户表(按之前的)
CREATE TABLE T_USER
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO T_USER (id, name, age, email) VALUES
(1, '张三', 13, 'zhangsan@qq.com'),
(2, '李四', 14, 'lisi@qq.com'),
(3, '王五', 15, 'wangwu@qq.com'),
(4, '赵六', 16, 'zhaoliu@qq.com'),
(5, '阿钟小哥', 18, 'azhongxiaoge@qq.com');
Role 角色表
CREATE TABLE t_role (
id BIGINT(20) NOT NULL COMMENT '主键ID',
rolecode VARCHAR(100) NULL DEFAULT NULL COMMENT '角色编号',
rolename VARCHAR(100) NULL DEFAULT NULL COMMENT '角色名字',
PRIMARY KEY (id)
);
INSERT INTO t_role(id, rolecode, rolename) VALUES
(1, '001', '董事长'),
(2, '002', 'CEO'),
(3, '003', 'CFO');
(4, '004', 'CTO');
Permission 权限表
CREATE TABLE t_permission (
id BIGINT(20) NOT NULL COMMENT '主键ID',
permissioncode VARCHAR(100) NULL DEFAULT NULL COMMENT '权限编号',
permissionname VARCHAR(100) NULL DEFAULT NULL COMMENT '权限名字',
path VARCHAR(100) NULL DEFAULT NULL COMMENT '映射路径',
PRIMARY KEY (id)
);
INSERT INTO t_permission(id, permissioncode, permissionname) VALUES
(1, '001', '招聘人才'),
(2, '002', '辞退庸才'),
(3, '003', '升职加薪');
UserRole 用户角色关联表
CREATE TABLE t_userrole (
id BIGINT(20) NOT NULL COMMENT '主键ID',
username VARCHAR(100) NULL DEFAULT NULL COMMENT '用户名',
rolecode VARCHAR(100) NULL DEFAULT NULL COMMENT '角色编号',
PRIMARY KEY (id)
);
INSERT INTO t_userrole(id, username, rolecode) VALUES
(1, '阿钟小哥', '001')
(2, '张三', '002'),
(3, '李四', '003'),
(4, '王五', '004')
(5, '赵六', '004');
RolePermission 角色权限关联表
CREATE TABLE t_rolepermission (
id BIGINT(20) NOT NULL COMMENT '主键ID',
rolecode VARCHAR(100) NULL DEFAULT NULL COMMENT '角色编号',
permissioncode VARCHAR(100) NULL DEFAULT NULL COMMENT '权限编号',
PRIMARY KEY (id)
);
INSERT INTO t_rolepermission(id, rolecode, permissioncode) VALUES
(1, '001', '001'),
(2, '002', '002'),
(3, '003', '003');
2. 创建实体类
文件路径:com.test.pojo
User 类
@Data
@TableName("user")
@ApiModel("用户类")
public class User implements Serializable {
@ApiModelProperty(name = "id", value = "ID 主键")
@TableId(type = IdType.AUTO)
private String id;
@ApiModelProperty(name = "name", value = "用户名")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String name;
@ApiModelProperty(name = "age", value = "年龄")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Integer age;
@ApiModelProperty(name = "email", value = "邮箱")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String email;
@TableField(exist = false)
private Set<Role> roles = new HashSet<>();
}
【简单理解】代码中 @ApiModel 和 @ApiModelProperty 注解出自于 Swagger 这块 API 简化开发开源框架,感兴趣的话可以去了解一下。
在 Springboot 中使用,需要在 pom.xml 文件中引入其依赖。
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
另外,也可以单独引入它的依赖,可自己指定对应或最新版本。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>lastest version</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>lastest version</version>
</dependency>
Role 类
@Data
@TableName("role")
@ApiModel("角色类")
public class Role implements Serializable {
@ApiModelProperty(name = "id", value = "ID 主键")
@TableId(type = IdType.AUTO)
private String id;
@ApiModelProperty(name = "roleCode", value = "角色编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String roleCode;
@ApiModelProperty(name = "roleName", value = "角色名")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String roleName;
@TableField(exist = false)
private Set<Permission> permissions = new HashSet<>();
}
Permission 类
@Data
@TableName("permission")
@ApiModel("权限类")
public class Permission implements Serializable {
@ApiModelProperty(name = "id", value = "ID 主键")
@TableId(type = IdType.AUTO)
private String id;
@ApiModelProperty(name = "permissionCode", value = "权限编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String permissionCode;
@ApiModelProperty(name = "permissionName", value = "权限名")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String permissionName;
@ApiModelProperty(name = "path", value = "映射路径")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String path;
}
UserRole 类
@Data
@TableName("userRole")
@ApiModel("用户角色关系类")
public class UserRole implements Serializable{
@ApiModelProperty(name = "id", value = "ID 主键")
@TableId(type = IdType.AUTO)
private String id;
@ApiModelProperty(name = "username", value = "用户名")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String username;
@ApiModelProperty(name = "roleCode", value = "角色编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Integer roleCode;
}
RolePermission 类
@Data
@TableName("rolePermission")
@ApiModel("角色权限关系类")
public class RolePermission implements Serializable{
@ApiModelProperty(name = "id", value = "ID 主键")
@TableId(type = IdType.AUTO)
private String id;
@ApiModelProperty(name = "roleCode", value = "角色编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Integer roleCode;
@ApiModelProperty(name = "permission", value = "权限编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String permissionCode;
}
3. 创建 Mapper 接口类
文件路径:com.test.mapper
UserMapper 接口类
public interface UserMapper extends BaseMapper<User> {
@Select("select * from t_user where name = #{name}")
public User findUserByName(String username);
// 获取用户所拥有的角色
@Select("select * from t_role where rolecode in(select rolecode from t_userrole where username = #{userName})")
public Set<Role> getUserRoles(String username);
}
RoleMapper 接口类
public interface RoleMapper extends BaseMapper<User> {
// 获取角色所拥有权限
@Select("select * from t_permission where permissioncode in (select permissioncode from t_rolepermission where rolecode = #{roleCode})")
public Set<Permission> getRolePermissions(String roleCode);
}
4. 在启动类中扫描 mapper
@SpringBootApplication
@MapperScan("com.test.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
5. 编辑 application.yml 文件
mybatis-plus:
type-aliases-package: com.test.pojo
configuration:
map-underscore-to-camel-case: true
6. 一起愉快地测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Test
public void testUserRole() {
User user = userMapper.findUserByName("阿钟小哥");
Set<Role> roles = userMapper.getUserRoles("阿钟小哥");
for (Role role : roles) {
role.setPermissions(roleMapper.getRolePermissions(role.getRoleCode()));
}
user.setRoles(roles);
System.out.println(user);
}
}