做后端开发的,无一不知晓mybatis的存在。它方便了sql的抒写,让项目更加的层次分明。但是mybaitis-plus的出现,将这个框架的方便程度再次升级了一个档次。我们公司的实际项目大多采用这个框架,这个框架不但集成了mybatis的所有功能,在一定程度上还增加了一些CRUD的接口。如果你的项目比较简单,并且涉及到的表查询基本都是单表的话,那我强烈建议你使用mybatis-plus,它会帮你省去70%的时间,你只需要关注业务即可。
本篇博文主要讲的是:如何快速使用mybaits-plus3.10,以及一些crud的相关接口参考。
环境:j、Java8+Spring boot2.2.4+Mybaits-plus3.1.0+mysql5.7.28
-
数据库表字段的建立,各个层次的代码的自动生成
创建一个表,表名为test_plus,具体的字段类型如下sql。
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for test_plus
-- ----------------------------
DROP TABLE IF EXISTS `test_plus`;
CREATE TABLE `test_plus` (
`ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '测试表的主键ID',
`username` varchar(300) DEFAULT NULL COMMENT '用户的姓名',
`password` varchar(300) DEFAULT NULL COMMENT '用户的密码',
`email` varchar(200) DEFAULT NULL COMMENT '用户的邮箱账号',
`email_password` varchar(400) DEFAULT NULL COMMENT '邮箱的密码',
`create_time` datetime DEFAULT NULL COMMENT '创建的时间',
`age` int(3) DEFAULT NULL COMMENT '用户的年龄',
PRIMARY KEY (`ID`),
KEY `name` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET FOREIGN_KEY_CHECKS = 1;
引入的jar,第一个是自动生成代码所需,第二个就是结合springboot的jar,freemarker也是需要的,这里说一下自动生成的代码包括一下:controller,service,serviceImpl,mapper,mapper.xml,entity
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
自动生成代码的工具类,复制下来改成你的数据库和数据库的密码,修改你的包路径即可。
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author:PSY
* @date:2020/2/14
* @description:自动生成器
*/
public class MybatisPlusCodeUtil {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
System.out.println("项目的目录为:"+projectPath);
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("psy");
gc.setOpen(false);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/xtzn_cpa?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.xtzn.cpa");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
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 projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// 命名规则
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("com.example.mybatisplus.common.BaseEntity");
// 实体是否使用Lombok插件
strategy.setEntityLombokModel(true);
// 控制层是否使用Rest风格
strategy.setRestControllerStyle(true);
//strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
strategy.setInclude(scanner("表名").split(","));
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
我数据库是本机的,修改为本机后,运行main方法,输入对应的表名:test_plus。成功在对应的文件夹下生成类对应文件。我这里的包名统一为:com.xtzn.cpa。
可以看到,实体类都是采用的驼峰命名方式,而且和数据库的字段是对应的。其他层的就不一一列出了,自己生成的时候就可以看到。
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="TestPlus对象", description="")
public class TestPlus implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "测试表的主键ID")
@TableId(value = "ID", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "用户的姓名")
private String username;
@ApiModelProperty(value = "用户的密码")
private String password;
@ApiModelProperty(value = "用户的邮箱账号")
private String email;
@ApiModelProperty(value = "邮箱的密码")
private String emailPassword;
@ApiModelProperty(value = "创建的时间")
private LocalDateTime createTime;
@ApiModelProperty(value = "用户的年龄")
private Integer age;
}
-
Spring boot项目配置,实现crud(springboot的搭建这里不再作说明)。
下面是spring boot配置文件中增加mybaits-plus的配置 ,说明都有。
mybatis-plus:
# xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.xtzn.cpa.entity
# 以下配置均有默认值,可以不设置
global-config:
db-config:
#主键类型 auto:"数据库ID自增" 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: auto
#字段策略 IGNORED:"忽略判断" NOT_NULL:"非 NULL 判断") NOT_EMPTY:"非空判断"
field-strategy: NOT_EMPTY
#数据库类型
db-type: MYSQL
configuration:
# 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
map-underscore-to-camel-case: true
# 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
call-setters-on-nulls: true
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
至此,我们代码有了,配置也有了,就可以实现简单的curd了。