Mybatisplus代码生成 之SpringBoot适配MYSQL和ORACLE
文章目录
- 前期准备:
- 看图操作,一路下一步
- 1. 导入相关依赖
- 2. 新建代码生成类MysqlGenerator
- 2.1. MYSQL 代码生成部分
- 2.2. ORACLE代码生成部分
- 3. 创建全局配置文件
- 4. 启动类加@MapperScan注解
- 5. 在controller层写个测试方法:
- 6. 浏览器验证
- 7. 多模块适配Mybatisplus代码生成 之SpringBoot适配MYSQL和ORACLE
前期准备:
- MYSQL数据库表
CREATE TABLE `tbl_employee` (`id` int(11) NOT NULL AUTO_INCREMENT,`last_name` varchar(50) COLLATE utf8_bin DEFAULT NULL,`email` varchar(50) COLLATE utf8_bin DEFAULT NULL,`gender` char(1) COLLATE utf8_bin DEFAULT NULL,`age` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
测试数据
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Tom','tom@atguigu.com',1,22);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Jerry','jerry@atguigu.com',0,25);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Black','black@atguigu.com',1,30);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('White','white@atguigu.com',0,35)
- user
CREATE TABLE `user` (`id` bigint(20) NOT NULL COMMENT '主键ID',`name` varchar(30) COLLATE utf8_bin DEFAULT NULL COMMENT '姓名',`age` int(11) DEFAULT NULL COMMENT '年龄',`email` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT '邮箱',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
测试数据
DELETE FROM user;INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
看图操作,一路下一步
搭建SpringBoot基础环境完成!!!
1. 导入相关依赖
<?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"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.gblfy</groupId><artifactId>mybatis-plus-generator</artifactId><version>0.0.1-SNAPSHOT</version><name>mybatis-plus-generator</name><description>Demo project for Spring Boot</description><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><mybatisplus.version>3.1.2</mybatisplus.version><oracle.version>11.2.0.3</oracle.version></properties><dependencies><!--mybatis-plus Start--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatisplus.version}</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>${mybatisplus.version}</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>${mybatisplus.version}</version></dependency><!--mybatis-plus End--><!-- lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</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-freemarker</artifactId></dependency><!--MYSQL数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- ORACLE数据库驱动--><dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>${oracle.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>3.1</version><configuration><source>${java.version}</source><target>${java.version}</target></configuration></plugin></plugins></build></project>
2. 新建代码生成类MysqlGenerator
2.1. MYSQL 代码生成部分
package com.gblfy.mybatisplus.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;/*** <p>* mysql 代码生成器演示例子* </p>** @author gblfy* @since 2019-07-12*/
public class MysqlGenerator {/*************************************MYSQL代码生成 Start *************************************/// 全局配置private final static String OUTPUT_XML_DIR = "/src/main/resources";// 生成xml文件的输出目录private final static String AUTHOR = "gblfy";// 开发人员// 数据源配置private final static String MYSQL_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";// MYSQL数据库驱动private final static String DATABASE_IP = "localhost";// 数据库ipprivate final static String MYSQL_DATABASE_NAME = "mp";// 数据库名private final static String MYSQL_DB_USERNAME = "root";// 数据库用户private final static String MYSQL_DB_PASSWORD = "root";// 数据库口令private final static String MYSQL_DB_PORT = "3306";// MYSQL数据库端口//包名和数据库表private final static String PARENT_PACKAGE = "com.gblfy.mybatisplus.generator";// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名private final static String MODULE_NAME = "emp";// 父包模块名private final static String[] TABLE_NAME_LIST = {"tbl_employee", "user"};// 父包模块名// 自定义基类private final static String SuperEntity = PARENT_PACKAGE + ".common.BaseEntity";private final static String SuperController = PARENT_PACKAGE + ".common.BaseController";/*** 运行main方法即可* 1.全局配置* 2.数据源配置* 3.包配置策略* 4.策略配置* 5.整合配置*/public static void main(String[] args) {//获取项目本地磁盘路径String projectPath = System.getProperty("user.dir");
/********************************** 全局配置**********************************/// 全局配置GlobalConfig gc = new GlobalConfig();//生成java文件的存放位置gc.setOutputDir(projectPath + "/src/main/java").setAuthor(AUTHOR)//作者署名.setFileOverride(true)//是否文件覆盖.setIdType(IdType.ID_WORKER)//主键策略.setBaseResultMap(true).setBaseColumnList(true)//生成sql片段//.setServiceName("%sService")//设置生成service接口是否首字母是I//是否打开输出目录.setOpen(false);
/********************************** 数据源配置**********************************///1.MYSQLDataSourceConfig dsc = new DataSourceConfig();dsc.setDbType(DbType.MYSQL)//设置数据库类型.setDriverName(MYSQL_DRIVER_NAME)//设置数据库启动.setUrl("jdbc:mysql://" + DATABASE_IP + ":" + MYSQL_DB_PORT + "/" + MYSQL_DATABASE_NAME + "?useUnicode=true&useSSL=false&characterEncoding=utf8").setDriverName(MYSQL_DRIVER_NAME).setUsername(MYSQL_DB_USERNAME).setPassword(MYSQL_DB_PASSWORD);
/********************************** 包名配置**********************************/// 包配置PackageConfig pc = new PackageConfig();pc.setParent(PARENT_PACKAGE).setModuleName(MODULE_NAME).setController("controller").setService("service").setServiceImpl("service.impl").setMapper("mapper");// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};List<FileOutConfig> focList = new ArrayList<>();focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输入文件名称 单模块场景return projectPath + OUTPUT_XML_DIR + "/mapper/" + pc.getModuleName()+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});cfg.setFileOutConfigList(focList);
/********************************** 策略配置**********************************/// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setCapitalMode(true)//全局大小写命名.setColumnNaming(NamingStrategy.underline_to_camel)//数据库字段是否下划线转驼峰.setNaming(NamingStrategy.underline_to_camel)//数据库表映射到实体的命名策略.setSuperEntityClass(SuperEntity).setEntityLombokModel(true).setSuperControllerClass(SuperController).setInclude(TABLE_NAME_LIST).setSuperEntityColumns("id").setControllerMappingHyphenStyle(true).setTablePrefix(pc.getModuleName() + "_");// 配置整合 代码生成器AutoGenerator mpg = new AutoGenerator();//配置信息添加至 全局配置容器mpg.setGlobalConfig(gc).setStrategy(strategy).setDataSource(dsc).setPackageInfo(pc).setCfg(cfg).setTemplate(new TemplateConfig().setXml(null)).setTemplateEngine(new FreemarkerTemplateEngine())// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!.execute();//执行}/*************************************MYSQL代码生成 End *************************************/
}
2.2. ORACLE代码生成部分
package com.gblfy.mybatisplus.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;/*** <p>* mysql 代码生成器演示例子* </p>** @author gblfy* @since 2019-07-12*/
public class MysqlGenerator {/*************************************ORACLE代码生成 Start *************************************/// 全局配置private final static String OUTPUT_XML_DIR = "/src/main/resources";// 生成xml文件的输出目录private final static String AUTHOR = "gblfy";// 开发人员// 数据源配置private final static String ORACLE_DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";// ORACLE数据库驱动private final static String DATABASE_IP = "xx.x.x.x";// 数据库ipprivate final static String ORACLE_DATABASE_NAME = "h";// 数据库名称private final static String ORACLE_DB_USERNAME = "root";// 数据库用户private final static String ORACLE_DB_PASSWORD = "root";// 数据库口令private final static String ORACLE_DB_PORT = "1521";// ORACLE数据库端口// 包和数据库表配置private final static String MODULE_NAME = "acc";// 父包模块名private final static String PARENT_PACKAGE = "com.gblfy.mybatisplus.generator";// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名private final static String[] TABLE_NAME_LIST = {"USER"};// 父包模块名// 自定义基类private final static String SuperEntity = PARENT_PACKAGE + ".common.BaseEntity";private final static String SuperController = PARENT_PACKAGE + ".common.BaseController";/*** 运行main方法即可* 1.全局配置* 2.数据源配置* 3.包配置策略* 4.策略配置* 5.整合配置*/public static void main(String[] args) {//获取项目本地磁盘路径String projectPath = System.getProperty("user.dir");
/********************************** 全局配置**********************************/// 全局配置GlobalConfig gc = new GlobalConfig();//生成java文件的存放位置gc.setOutputDir(projectPath + "/src/main/java").setAuthor(AUTHOR)//作者署名.setFileOverride(true)//是否文件覆盖.setIdType(IdType.ID_WORKER)//主键策略.setBaseResultMap(true).setBaseColumnList(true)//生成sql片段//.setServiceName("%sService")//设置生成service接口是否首字母是I//是否打开输出目录.setOpen(false);
/********************************** 数据源配置**********************************/DataSourceConfig dsc = new DataSourceConfig();dsc.setDbType(DbType.ORACLE)//设置数据库类型.setUrl("jdbc:oracle:thin:@" + DATABASE_IP + ":" + ORACLE_DB_PORT + ":" + ORACLE_DATABASE_NAME).setDriverName(ORACLE_DRIVER_NAME).setUsername(ORACLE_DB_USERNAME).setPassword(ORACLE_DB_PASSWORD);
/********************************** 包名配置**********************************/// 包配置PackageConfig pc = new PackageConfig();pc.setParent(PARENT_PACKAGE).setModuleName(MODULE_NAME).setController("controller").setService("service").setServiceImpl("service.impl").setMapper("mapper");// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};List<FileOutConfig> focList = new ArrayList<>();focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输入文件名称 单模块场景return projectPath + OUTPUT_XML_DIR + "/mapper/" + pc.getModuleName()+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});cfg.setFileOutConfigList(focList);
/********************************** 策略配置**********************************/// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setCapitalMode(true)//全局大小写命名.setColumnNaming(NamingStrategy.underline_to_camel)//数据库字段是否下划线转驼峰.setNaming(NamingStrategy.underline_to_camel)//数据库表映射到实体的命名策略.setSuperEntityClass(SuperEntity).setEntityLombokModel(true).setSuperControllerClass(SuperController).setInclude(TABLE_NAME_LIST).setSuperEntityColumns("id").setControllerMappingHyphenStyle(true).setTablePrefix(pc.getModuleName() + "_");// 配置整合 代码生成器AutoGenerator mpg = new AutoGenerator();//配置信息添加至 全局配置容器mpg.setGlobalConfig(gc).setStrategy(strategy).setDataSource(dsc).setPackageInfo(pc).setCfg(cfg).setTemplate(new TemplateConfig().setXml(null)).setTemplateEngine(new FreemarkerTemplateEngine())// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!.execute();//执行}/*************************************MYSQL代码生成 End *************************************/}
3. 创建全局配置文件
# Mysql数据库
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/mp?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTTusername: rootpassword: root# Logger Config
logging:level:com.gblfy.mybatisplus.generator: debug
4. 启动类加@MapperScan注解
package com.gblfy.mybatisplus.generator;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.gblfy.mybatisplus.generator.emp.mapper")
public class MybatisPlusGeneratorApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusGeneratorApplication.class, args);}
}
5. 在controller层写个测试方法:
package com.gblfy.mybatisplus.generator.emp.controller;import com.gblfy.mybatisplus.generator.common.BaseController;
import com.gblfy.mybatisplus.generator.emp.entity.TblEmployee;
import com.gblfy.mybatisplus.generator.emp.service.ITblEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;/*** <p>* 前端控制器* </p>** @author gblfy* @since 2019-07-13*/
@Controller
@RequestMapping("/emp/tbl-employee")
public class TblEmployeeController extends BaseController {@Autowiredprivate ITblEmployeeService employeeService;@RequestMapping("")@ResponseBodypublic List<TblEmployee> list() {List<TblEmployee> list = employeeService.list();return list;}
}
6. 浏览器验证
http://localhost:8080/emp/tbl-employee
7. 多模块适配Mybatisplus代码生成 之SpringBoot适配MYSQL和ORACLE
多模块适配只是目录有所他调整而已
package com.baomidou.mybatisplus.samples.generator;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;/*** <p>* mysql 代码生成器演示例子* </p>** @author jobob* @since 2018-09-12*/
public class MysqlGenerator {// 全局配置private final static String PROJECT_DIR = "/mybatis-plus-sample-generator";// 项目名称private final static String OUTPUT_JAVA_DIR = PROJECT_DIR + "/src/main/java";// 生成java文件的输出目录private final static String OUTPUT_XML_DIR = PROJECT_DIR + "/src/main/resources";// 生成xml文件的输出目录private final static String AUTHOR = "gblfy";// 开发人员// 数据源配置private final static String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";// 数据库驱动private final static String DATABASE_IP = "localhost";// 数据库ipprivate final static String DATABASE_NAME = "mp";// 数据库名称private final static String DB_USERNAME = "root";// 数据库用户private final static String DB_PASSWORD = "root";// 数据库口令// 包配置private final static String PARENT_PACKAGE = "com.baomidou.mybatisplus.samples.generator";// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名private final static String MODULE_NAME = "empl";// 父包模块名private final static String[] TABLE_NAME_LIST = {"tbl_employee", "user"};// 父包模块名// 自定义基类private final static String SuperEntity = PARENT_PACKAGE + ".common.BaseEntity";private final static String SuperController = PARENT_PACKAGE + ".common.BaseController";/*** <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 + "!");}/*** RUN THIS*/public static void main(String[] args) {// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");System.out.println("projectPath" + projectPath);/***projectPath 代表父工程的本地磁盘位置* /mybatis-plus-sample-generator :子项目位置* 多模块场景* 格式:projectPath+子项目位置** 单模块* 格式:projectPath*/gc.setOutputDir(projectPath + OUTPUT_JAVA_DIR);gc.setAuthor(AUTHOR);gc.setOpen(false);mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://" + DATABASE_IP + ":3306/" + DATABASE_NAME + "?useUnicode=true&useSSL=false&characterEncoding=utf8");dsc.setDriverName(DRIVER_NAME);dsc.setUsername(DB_USERNAME);dsc.setPassword(DB_PASSWORD);mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));pc.setModuleName(MODULE_NAME);pc.setParent(PARENT_PACKAGE);mpg.setPackageInfo(pc);// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};List<FileOutConfig> focList = new ArrayList<>();focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输入文件名称return projectPath + OUTPUT_XML_DIR + "/mapper/" + pc.getModuleName()+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);mpg.setTemplate(new TemplateConfig().setXml(null));// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);strategy.setSuperEntityClass(SuperEntity);strategy.setEntityLombokModel(true);strategy.setSuperControllerClass(SuperController);
// strategy.setInclude(new String[]{"tbl_employee", "user"});strategy.setInclude(TABLE_NAME_LIST);strategy.setSuperEntityColumns("id");strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix(pc.getModuleName() + "_");mpg.setStrategy(strategy);// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();}}