文章目录
- MyBatis Plus 基础篇
- MyBatis Plus 核心功能篇
- MyBatis Plus 常用插件
MyBatis Plus 基础篇
一、简介
MyBatis 是一个半自动的 ORM 框架。
MyBatis-Plus(简称 MP)是一个 MyBatis 的 增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
【提示】当前最新的版本 3.1.1。
三、基本开发环境
- 基于 Java 开发,建议 jdk 1.8+ 版本。
- 需要使用到 Spring Boot
- 需要使用到 Maven
- 需要使用 MySQL
1. 准备数据
我们需要准备一张 user 表
DROP TABLE IF EXISTS user;
CREATE TABLE 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)
);
然后给 user 表中添加一些数据
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, '翠花', 18, '[email protected]'),
(2, '春花', 20, '[email protected]'),
(3, '花花', 28, '[email protected]'),
(4, '翠翠', 21, '[email protected]'),
(5, '春春', 24, '[email protected]');
2. Hello World
我们的目的:通过几个简单的步骤,我们就实现了 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/aaa?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: 1234
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.kkb.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.kkb.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> {
}
第五步:愉快地测试
新建 KKBTest 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
@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("[email protected]");
user.setAge(18);
userMapper.insert(user);
// 4. 更新数据
user.setName("老王王");
user.setEmail("[email protected]");
userMapper.updateById(user);
}
}
四、常见注解
- @TableName:表名描述
- @TableId:主键注释
- @TableField:字段注解(非主键)
- @Version:乐观锁注解,主要用于标注在字段上
- @EnumValue:通枚举类注解(注解在枚举字段上)
- @TableLogic:表字段逻辑处理注解(逻辑删除)
- @SqlParser:租户注解(支持注解在 mapper 上)
- @KeySequence:序列主键策略,属性有:value、resultMap
案例:多表联查
1. 准备数据
User 用户表(按之前的)
CREATE TABLE 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 USER (id, NAME, age, email) VALUES
(1, 'cuihua', 18, '[email protected]'),
(2, 'huahua', 20, '[email protected]'),
(3, 'cunhua', 28, '[email protected]'),
(4, 'laowang', 21, '[email protected]'),
(5, 'xiaomei', 24, '[email protected]');
Role 角色表
CREATE TABLE 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 role(id, rolecode, rolename) VALUES
(1, '001', '总裁'),
(2, '002', '院长'),
(3, '003', '组长');
Permission 权限表
CREATE TABLE 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 permission(id, permissioncode, permissionname) VALUES
(1, '111', '随便乱来'),
(2, '222', '偶尔乱来'),
(3, '333', '小小乱来');
UserRole 用户角色关联表
CREATE TABLE 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 userrole(id, username, rolecode) VALUES
(1, 'cuihua', '001'),
(2, 'chunhua', '003'),
(3, 'huahua', '002');
RolePermission 角色权限关联表
CREATE TABLE 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 rolepermission(id, rolecode, permissioncode) VALUES
(1, '001', '111'),
(2, '002', '222'),
(3, '003', '333');
2. 创建实体类
文件路径:com.kkb.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>