前言
本文章将演示SpringBoot整合Mybatis-Plus以及常用常用注解方法
一、Mybatis-Plus简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window) 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
二、框架结构
通过结构图可以看出MyBatisPlus专门提供了mybatis-plus-boot-starter供SpringBoot使用
三、SpringBoot整合Mybatis-Plus
1.依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
注:此依赖整合了Mybatis和Mybatis-Plus,所以尽量不要再加mybatis的依赖,以免冲突
2.配置文件设置
mybatis:
configuration:
//默认是不允许自动转换驼峰命名,得自己设置为true
map-underscore-to-camel-case: true
//起别名
type-aliases-package: com.apesource.pojo
mybatis-plus:
configuration:
//默认是允许自动转换驼峰命名
map-underscore-to-camel-case: true
//开启日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
注:mybatis和mybatis-plusd 配置是相互独立且生效的
四、前期准备
4.1数据库信息
4.2dao类
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
dao层的接口使用@Mapper声明可以被自动注入,并且继承Mybatis-Plus提供的BaseMapper类实现通过mapper对象调用CDUR方法
4.3pojo类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {
private int stuId;
private String stuName;
private String stuNick;
private String stuHobby;
private int stuAge;
private int deleted;
public Student(String stuName, String stuNick, String stuHobby, int stuAge) {
this.stuName = stuName;
this.stuNick = stuNick;
this.stuHobby = stuHobby;
this.stuAge = stuAge;
}
public Student(String stuName, String stuNick, String stuHobby) {
this.stuName = stuName;
this.stuNick = stuNick;
this.stuHobby = stuHobby;
}
}
五、常用注解
5.1 @TableName(value = “”)
作用:将类对应到数据库的某个表上
位置:类
参数:value=表的字段名
5.2 @TableId(value=“”,type = IdType.XXX)
作用:将数据库的主键字段映射到类的属性中
位置:成员变量
参数:value=表的字段名;type=AUTO(0),NONE(1),INPUT(2),ASSIGN_ID(3),ASSIGN_UUID(4);
5.3 @TableField(“”)
作用:将类的属性映射到表的字段
位置:成员变量
参数:value=表的字段名
5.4@TableLogic(value = “0”,delval = “1”)
作用:开启逻辑删除,0表示未删除,1表示以及删除
位置:成员变量
参数:value=正常状态的值,delval=被删除后的值
注:此注解声明的成员变量只有MybatisPlus能识别,如果使用mybatis的方法查询的话,还是能查询到状态是已删除的信息
将以上注解用与Studen类中
@TableName(value = "student")
public