Mybatis-Plus学习总结
Mybatis-plus官网:https://baomidou.com/
Mybatis-plus详细教程:https://www.hxstrive.com/subject/mybatis_plus.htm
Mybatis-plus简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
Mybatis-plus项目
- Spring Boot 2.5.0
- mybatis-plus 3.4.0
- Mysql 8.0.25
- lombok
- Swagger2 2.9.2
一、准备工作
在创建项目之前,这里首先准备了一张用户信息表
user_info,相应的sql脚本如下:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`available` int(1) NULL DEFAULT 1 COMMENT '是否可用,1 可用,0 不可用',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`deleted` int(1) NULL DEFAULT 0 COMMENT '是否删除,0 未删除, 1 删除',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
`avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像',
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
`phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号',
`salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '盐',
`sex` int(1) NULL DEFAULT NULL COMMENT '性别 0未知 1女 2男',
`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 33 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户信息表' ROW_FORMAT = Dynamic;
INSERT INTO `user_info` VALUES (1, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (2, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (3, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (4, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (5, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (6, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (7, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (8, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (9, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
INSERT INTO `user_info` VALUES (10, 1, '2021-05-14 13:30:32', 0, '2021-05-19 15:19:15', NULL, '12345678@qq.com', '123456', '12345678910', '12', 1, '张三');
SET FOREIGN_KEY_CHECKS = 1;
二、创建一个Spring Boot项目
三、添加所需依赖
在项目的pom.xml文件中添加如下依赖
<!--mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!--引入mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
四、在项目的application.yml配置文件中,配置如下信息
spring:
application:
name: mybatis-plus
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
logging:
level:
com:
example:
mybatisplus:
mapper: trace
root: warn
pattern:
console: '%p%m%n'
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
注:新建的项目默认配置文件是application.properties,在这里习惯使用yml文件格式。
.yml文件与.properties文件相互转化工具:https://www.toyaml.com/index.html
五、创建实体类
BaseEntity.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "是否删除,0 未删除, 1 删除")
@TableLogic(value = "0",delval = "1")
@TableField(value = "deleted", fill = FieldFill.INSERT)
private Integer deleted;
@ApiModelProperty(value = "是否可用,1 可用,0 不可用")
@TableField(value = "available", fill = FieldFill.INSERT)
private Integer available;
@ApiModelProperty(value = "创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@ApiModelProperty(value = "修改时间")
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
UserInfo.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("user_info") //定义表名
@ApiModel(value="UserInfo对象", description="用户信息表")
public class UserInfo extends BaseEntity {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "头像")
@TableField("avatar")
private String avatar;
@ApiModelProperty(value = "邮箱")
@TableField("email")
private String email;
@ApiModelProperty(value = "密码")
@TableField("password")
private String password;
@ApiModelProperty(value = "手机号")
@TableField("phone")
private String phone;
@ApiModelProperty(value = "盐")
@TableField("salt")
private String salt;
@ApiModelProperty(value = "性别 0未知 1女 2男")
@TableField("sex")
private Integer sex;
@ApiModelProperty(value = "姓名")
@TableField("user_name")
private String userName;
}
六、创建mapper接口
UserInfoMapper.java
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
可以明显看到,上面代码中没有自定义任何自己的方法,所有方法均从 BaseMapper 父接口继承而来。
七、添加mapper接口扫描路径配置
使用 @MapperScan 注解 在Spring Boot的启动类添加mapper接口的扫描路径配置,扫描 com.example.mybatisplus.mapper 包下面的所有 mapper!!!
@SpringBootApplication
@MapperScan("com.example.mybatisplus.mapper")
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
八、编写一个简单Controller
编写一个简单的controller,使用@Autowired 注解自动注入自定义的 mapper
UserInfoController.java
@RestController
@RequestMapping("/api/userInfo")
@Api(value = "/api/userInfo", tags = {
"用户信息表接口"})
public class UserInfoController {
@Autowired
private UserInfoMapper userInfoMapper;
@GetMapping
public List findAllUserList(){
List<UserInfo> list = userInfoMapper.selectList(null);
return list;
}
}
九、启动项目,进行简单测试
关于更多Mybatis-plus详细知识:
- BaseMapper 接口 CRUD
- Service CRUD 接口
- 条件构造器
- 常用注解
- 代码生成器
可以查看https://www.hxstrive.com/subject/mybatis_plus.htm
这里将不对每个知识点进行演示啦!!!
代码生成器
AutoGenerator
是 MyBatis-Plus 的代码生成器,通过 AutoGenerator
可以快速生成 Entity
、Mapper
、Mapper XML
、Service
、Controller
等各个模块的代码,极大的提升了开发效率。
代码演示
注:下面代码示例基于上面项目,所有代码在generator包下面。此外需要添加下面的依赖。
一、添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
二、编写工具类
Config.java
package com.example.generator.config;
/**
* @Author:
* @Description:
* @CreateDate: 2021-05-25 14:49
* @Version: 1.0
*/
public class Config {
public static String URL = "jdbc:mysql://127.0.0.1:3306/hang?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true";
public static String USERNAME = "root";
public static String PASSWORD = "123456";
public static String DRIVER = "com.mysql.cj.jdbc.Driver";
public static String TABLE_NAME = "sys_user,sys_role,sys_file"; //多个表明用,连接
/**
* 包名
*/
public static final String PACKAGE_PARENT = "com.example";
/**
* 文件名后缀:Dao
*/
public static final String FILE_NAME_DAO = "%sMapper";
/**
* 文件名后缀:MapperXml
*/
public static final String FILE_NAME_XML = "%sMapper";
/**
* MP开头,Service结尾
*/
public static final String FILE_NAME_SERVICE = "%sService";
/**
* 文件名后缀:ServiceImpl
*/
public static final String FILE_NAME_SERVICE_IMPL = "%sServiceImpl";
/**
* 文件名后缀:Controller
*/
public static final String FILE_NAME_CONTROLLER = "%sController";
/**
* 逻辑删除字段
*/
public static final String FIELD_LOGIC_DELETE_NAME = "deleted";
/**
* 作者
*/
public static final String AUTHOR = "generator";
/**
* 生成文件的输出目录
*/
// public static String projectPath = System.getProperty("user.dir") + "/mp-generator";
public static String projectPath = System.getProperty("user.dir");
/**
* 输出目录
*/
public static final String outputDir = projectPath + "/src/main/java";
/**
* 模板引擎。velocity / freemarker / beetl
*/
public static final String TEMPLATE_ENGINE = "freemarker";
/**
* 是否支持Swagger,默认不支持
*/
public static final Boolean SWAGGER_SUPPORT = true;
}
CommonUtils.java
package com.example.generator.utils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.example.generator.config.Config;
import java.util.ArrayList;
import java.util.List;
/**
* @Author:
* @Description:
* @CreateDate: 2021-05-25 14:50
* @Version: 1.0
*/
public class CommonUtils {
// 配置
private static GlobalConfig globalConfig() {
return new GlobalConfig()
.setAuthor(Config.AUTHOR) //作者名称
.setOutputDir(Config.outputDir)
.setFileOverride(true) //是否覆盖已有文件
.setOpen(false) // 是否打开输出目录
.setDateType(DateType.ONLY_DATE) // 时间采用java 8,(操作工具类:JavaLib => DateTimeUtils)
.setEnableCache(false)// XML 二级缓存
.setBaseResultMap(false)// XML ResultMap
.setBaseColumnList(false)// XML columList
.setKotlin(false) //是否生成 kotlin 代码
.setMapperName(Config.FILE_NAME_DAO) //自定义文件命名,注意 %s 会自动填充表实体属性!
.setXmlName(Config.FILE_NAME_XML)
.setServiceName(Config.FILE_NAME_SERVICE)
.setServiceImplName(Config.FILE_NAME_SERVICE_IMPL)
.setControllerName(Config.FILE_NAME_CONTROLLER)
.setSwagger2(Config.SWAGGER_SUPPORT) // model swagger2
;
}
//数据源配置
private static DataSourceConfig dataSourceConfig() {
return new DataSourceConfig()
.setDbType(DbType.MYSQL)
.setUrl(Config.URL)
.setUsername(Config.USERNAME)
.setPassword(Config.PASSWORD)
.setDriverName(Config.DRIVER)
;
}
// 包信息配置
private static PackageConfig packageConfig() {
return new PackageConfig()
.setModuleName("code")
.setParent(Config.PACKAGE_PARENT)
// .setController(Config.PACKAGE_NAME_CONTROLLER)
// .setEntity(Config.PACKAGE_NAME_MODEL)
// .setMapper(Config.PACKAGE_NAME_DAO)
// .setXml(Config.PACKAGE_NAME_XML)
// .setService(Config.PACKAGE_NAME_SERVICE)
// .setServiceImpl(Config.PACKAGE_NAME_SERVICE_IMPL)
;
}
//实体类配置
private static StrategyConfig strategyConfig() {
return new StrategyConfig()
.setChainModel(true) // 【实体】是否为构建者模型(默认 false)
.setNaming(NamingStrategy.underline_to_camel)
.setColumnNaming(NamingStrategy.underline_to_camel)
// .setSuperEntityClass(BaseEntity.class)
.setEntityLombokModel(true)
.setRestControllerStyle(true)
.setInclude(Config.TABLE_NAME.split(",")) //数据库表名字
.setControllerMappingHyphenStyle(false)
.setEntityTableFieldAnnotationEnable(true) //是否生成实体时,生成字段注解,包括@TableName("")
;
}
private static InjectionConfig injectionConfig() {
InjectionConfig injectionConfig = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return Config.projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
injectionConfig.setFileOutConfigList(focList);
return injectionConfig;
}
// 获取模板引擎——使用freemarker模板引擎
private static AbstractTemplateEngine getTemplateEngine() {
String templateEngine = Config.TEMPLATE_ENGINE;
switch (templateEngine) {
case "velocity":
return new VelocityTemplateEngine();
case "freemarker":
return new FreemarkerTemplateEngine();
case "beetl":
return new BeetlTemplateEngine();
default:
return new VelocityTemplateEngine();
}
}
private static TemplateConfig templateConfig() {
TemplateConfig templateConfig = new TemplateConfig();
//配置自定义输出模板,指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
templateConfig.setController("templates/controllerGenerator.java");
templateConfig.setServiceImpl("templates/serviceImplGenerator.java");
templateConfig.setMapper("templates/mapperGenerator.java");
templateConfig.setEntity("templates/entityGenerator.java");
templateConfig.setXml(null);
return templateConfig;
}
// 执行器
public static void execute() {
GlobalConfig globalConfig = globalConfig();
DataSourceConfig dataSourceConfig = dataSourceConfig();
PackageConfig packageConfig = packageConfig();
StrategyConfig strategyConfig = strategyConfig();
InjectionConfig injectionConfig = injectionConfig();
AbstractTemplateEngine templateEngine = getTemplateEngine();
TemplateConfig templateConfig = templateConfig();
new AutoGenerator()
.setGlobalConfig(globalConfig)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(packageConfig)
.setTemplateEngine(templateEngine)
.setCfg(injectionConfig)
.setTemplate(templateConfig)
.execute();
}
}
三、编写生成器模板
自定义代码生成器模板
在项目的resources/templates文件夹下面创建以下模板文件:
controllerGenerator.java.ftl
package ${
package.Controller};
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${
superControllerClassPackage};
</#if>
/**
*
* @author ${author}
* @since ${date}
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("/api/mp-generator<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
@Api(value = "/api/mp-generator<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>", tags = {
"${table.comment!}接口"})
<#if kotlin>
class ${
table.controllerName}<#if superControllerClass??> : ${
superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${
table.controllerName} extends ${
superControllerClass} {
<#else>
public class ${
table.controllerName} {
</#if>
}
</#if>
serviceImplGenerator.java.ftl
package ${
package.ServiceImpl};
import ${
package.Entity}.${
entity};
import ${
package.Mapper}.${
table.mapperName};
import ${
package.Service}.${
table.serviceName};
import ${
superServiceImplClassPackage};
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
*
* @author ${author}
* @since ${date}
*/
@Slf4j
@Service
<#if kotlin>
open class ${
table.serviceImplName} : ${
superServiceImplClass}<${
table.mapperName}, ${
entity}>(), ${
table.serviceName} {
}
<#else>
public class ${
table.serviceImplName} extends ${
superServiceImplClass}<${
table.mapperName}, ${
entity}> implements ${
table.serviceName} {
}
</#if>
mapperGenerator.java.ftl
package ${
package.Mapper};
import ${
package.Entity}.${
entity};
import ${
superMapperClassPackage};
import org.springframework.stereotype.Repository;
/**
*
* @author ${author}
* @since ${date}
*/
@Repository
<#if kotlin>
interface ${
table.mapperName} : ${
superMapperClass}<${
entity}>
<#else>
public interface ${
table.mapperName} extends ${
superMapperClass}<${
entity}> {
}
</#if>
entityGenerator.java.ftl
package ${
package.Entity};
import lombok.*;
import java.io.Serializable;
/**
*
* @author ${author}
* @since ${date}
*/
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ${
entity} implements Serializable {
private static final long serialVersionUID = 1L;
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
private ${
field.propertyType} ${
field.propertyName};
</#list>
<#-------------- END 字段循环遍历 --------------->
}
四、测试
CodeGenerator.java
package com.example.generator;
import com.example.generator.utils.CommonUtils;
/**
* @Author:
* @Description:
* @CreateDate: 2021-05-25 14:53
* @Version: 1.0
* *******************************************
* 注:生成代码之前根据需要作以下修改:
* (1)config.Config.java 类中的数据库连接信息
* (2)config.Config.java 类中包名 PACKAGE_PARENT
* (3)config.Config.java 类中 TABLE_NAME 数据库表名,多个表明用,连接
*/
public class CodeGenerator {
public static void main(String[] args) {
//生成代码,执行此方法
CommonUtils.execute();
}
}
执行上面main方法即可生成!!!
生成后的文件结构
<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">
本篇文章到这里就基本结束了,如果这篇文章对你有帮助,希望大家能留下你的点赞、 关注、 分享、 留言❤️❤️❤️
最后的最后,附上源码下载地址:https://gitee.com/wst-taoge/mybatisplus