1.背景介绍
相信很多朋友在项目中使用的ORM框架都是MyBatis,如果单用MyBatis来操作数据库的话,需要手写很多单表查询的SQL实现。这时候我们往往会选择一个增强工具来实现这些单表CRUD操作,这里推荐一款好用的工具MyBatis-Plus!
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。MyBatis-Plus 提供了代码生成器,可以一键生成controller、service、mapper、model、mapper.xml代码,同时提供了丰富的CRUD操作方法,助我们解放双手!
2.mysql环境准备
mysql setup
docker run --name docker-mysql-5.7 -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql:5.7
init data
create database demo;
create table user_info
(
user_id varchar(64) not null primary key,
username varchar(100) null ,
age int(3) null ,
gender tinyint(1) null ,
remark varchar(255) null ,
create_time datetime null ,
create_id varchar(64) null ,
update_time datetime null ,
update_id varchar(64) null ,
enabled tinyint(1) default 1 null
);
INSERT INTO demo.user_info
(user_id, username, age, gender, remark, create_time, create_id, update_time, update_id, enabled)
VALUES('1', '1', 1, 1, '1', NULL, '1', NULL, NULL, 1);
remark
msyql username:root
mysql password:123456
3.代码工程
实验目标:基于mysql自动生成crud代码
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>generator</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- spring boot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
</dependencies>
</project>
工具生成类
package com.et.generator;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
public class Generator {
public static void main(String[] args) {
// System.getProperty("user.dir") == get current project dir
String projectDir ="D:\\IdeaProjects\\ETFramework\\generator";
String outputDir = projectDir+"\\src\\main\\java";
//String outputDir = System.getProperty("user.dir") + "/src/main/java";
// String outputDir = "C://Users/VULCAN/Desktop/new";
// table name, Pay attention to capitalization
String[] tableNames = new String[]{"user_info"};
// database url
String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8";
String userName = "root";
String password = "123456";
// parentPackage
String parentPackage = "com.et.generator";
// need to remove prefix from tablename
String prefixTable = "";
generate(projectDir,outputDir, tableNames, url, userName, password, parentPackage, prefixTable);
}
/**
* @param outputDir
* @param tableNames
* @param url
* @param userName
* @param password
* @param parentPackage
* @param prefixTable
*/
public static void generate(String projectDir,String outputDir, String[] tableNames, String url, String userName,
String password, String parentPackage, String prefixTable) {
// =============== Global setting ==================
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(outputDir)
.setActiveRecord(true) // enable AR,
.setAuthor("Harries") // set Author name
.setFileOverride(true) // enable FileOverride?
.setIdType(IdType.AUTO) //primary strategy
.setBaseResultMap(true) // SQL mappingg
.setBaseColumnList(true) // SQL BaseColumn
.setServiceName("%sService") // service name
.setOpen(false);
// ================= database setting ===============
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL)
.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUrl(url)
.setUsername(userName)
.setPassword(password);
// ================= package setting ===================
PackageConfig pc = new PackageConfig();
pc.setParent(parentPackage) // parentPackage path
// .setModuleName("base") // ModuleName path
.setMapper("mapper")
.setEntity("entity")
// .setEntity("entity")
.setService("service")
//.setServiceImpl("service.impl"); // auto generate impl, no need to set
.setController("controller");
// ================== custom setting =================
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
// adjust xml generate directory
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// custom file name
return projectDir + "/src/main/resources/mybatis/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
// =================== strategy setting ==================
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel) // table name: underline_to_camel
.setColumnNaming(NamingStrategy.underline_to_camel) // file name: underline_to_camel
.setInclude(tableNames) // tableNames
.setCapitalMode(true) // enable CapitalMod(ORACLE )
.setTablePrefix(prefixTable) // remove table prefix
// .setFieldPrefix(pc.getModuleName() + "_") // remove fields prefix
// .setSuperEntityClass("com.maoxs.pojo") // Entity implement
// .setSuperControllerClass("com.maoxs.controller") // Controller implement
// .setSuperEntityColumns("id") // Super Columns
// .setEntityLombokModel(true) // enable lombok
.setControllerMappingHyphenStyle(true); // controller MappingHyphenStyle
// ================== custome template setting:default mybatis-plus/src/main/resources/templates ======================
//default: src/main/resources/templates directory
TemplateConfig tc = new TemplateConfig();
tc.setXml(null) // xml template
.setEntity("/templates/entity.java") // entity template
.setMapper("/templates/mapper.java") // mapper template
.setController("/templates/controller.java") // service template
.setService("/templates/service.java") // serviceImpl template
.setServiceImpl("/templates/serviceImpl.java"); // controller template
// ==================== gen setting ===================
AutoGenerator mpg = new AutoGenerator();
mpg.setCfg(cfg)
.setTemplate(tc)
.setGlobalConfig(gc)
.setDataSource(dsc)
.setPackageInfo(pc)
.setStrategy(strategy)
.setTemplateEngine(new FreemarkerTemplateEngine()); // choose freemarker engine,pay attention to pom dependency!
mpg.execute();
}
}
模版文件
模版文件太多,这里就不贴出来来了,你可以在resource文件夹下查看具体内容
DemoApplication
package com.et.generator;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.et.generator.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
application.yaml
server:
port: 8088
spring:
datasource:
password: 123456
username: root
url: jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath*:/mybatis/*.xml
4.测试
生成
修改Generator类里面的一些生成参数,然后运行main方法生成对应的代码,效果如下
测试生成代码是否正确
启动Sring Boot应用,访问地址http://127.0.0.1:8088/userInfo/findAllUserInfo,返回结果如下:
[{"userId":"1","username":"1","age":1,"gender":true,"remark":"1","createTime":null,"createId":"1","updateTime":null,"updateId":null,"enabled":true},{"userId":"2","username":"2","age":2,"gender":true,"remark":"2","createTime":null,"createId":"2","updateTime":null,"updateId":null,"enabled":true}]
5.参考引用