6.Mybatis plus 代码生成器,mybatis-generator 插件使用

2019年10月15日 20:13 · 阅读(558) ·

说明

本文代码基于 5.基于 JWT(Json web token) 验证权限 项目代码进行修改,不过基本没关系

开发环境

名称 版本
操作系统 Windows 10 X64
JDK JDK1.8(jdk-8u151-windows-x64)
IntelliJ IDEA IntelliJ IDEA 2018.3
Maven Maven 3.6.0

根据开发文档创建表

1.开发文档

2.pom

  1. <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
  2. <dependency>
  3. <groupId>cn.hutool</groupId>
  4. <artifactId>hutool-all</artifactId>
  5. <version>5.7.9</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.poi</groupId>
  9. <artifactId>poi-ooxml</artifactId>
  10. <version>4.1.0</version>
  11. </dependency>

3.Java 代码

  1. public static void main(String[] args) {
  2. ExcelReader reader = ExcelUtil
  3. .getReader(FileUtil.file("C:\\Users\\luoma\\Desktop\\融资贷款\\融资数据表v1.1.xlsx"),
  4. 4);//配置路径和sheet页
  5. int startRow = 202;//表名那行
  6. int endRow = 218;//逻辑删除那行
  7. List<List<Object>> read = reader.read(startRow-1,endRow-1);
  8. String text = "CREATE TABLE `" + read.get(0).get(0) + "` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键ID',";
  9. for (List<Object> o : read){
  10. if (o.equals(read.get(0)) || o.equals(read.get(1)) || o.equals(read.get(2))){
  11. continue;
  12. }
  13. if ("VARCHAR".equalsIgnoreCase(String.valueOf(o.get(1))) || "text".equalsIgnoreCase(String.valueOf(o.get(1)))){
  14. String b = "`" + o.get(0) + "`" + " " + o.get(1) + "(" + o.get(2) + ") " + "COLLATE utf8mb4_bin DEFAULT NULL COMMENT " + "'" + o.get(3) + "',";
  15. text += b;
  16. }else if ("datetime".equalsIgnoreCase(String.valueOf(o.get(1))) || "date".equalsIgnoreCase(String.valueOf(o.get(1)))){
  17. String b = "`" + o.get(0) + "`" + " " + o.get(1) + " " + "DEFAULT NULL COMMENT " + "'" + o.get(3) + "',";
  18. text += b;
  19. }else {
  20. String b = "`" + o.get(0) + "`" + " " + o.get(1) + "(" + o.get(2) + ") " + "DEFAULT NULL COMMENT " + "'" + o.get(3) + "',";
  21. text += b;
  22. }
  23. }
  24. text += "PRIMARY KEY (`id`) USING BTREE,\n"
  25. + " KEY `tenant_id` (`tenant_id`) USING BTREE\n"
  26. + ") ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='" + read.get(0).get(0) + "';";
  27. System.err.println(text);
  28. }

Mybatis plus 代码生成器

测试表-t_rbt_test

测试表-t_rbt_test

创建子模块-test-invoice-generator

test-invoice-cloud 上右键,新建模块

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

ArtifactId test-invoice-common

模块名称 test-invoice-common

创建类和文件

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-generator</artifactId>
  12. <name>test-invoice-generator</name>
  13. <dependencies>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-jdbc</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-web</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-test</artifactId>
  25. <scope>test</scope>
  26. </dependency>
  27. <dependency>
  28. <groupId>com.baomidou</groupId>
  29. <artifactId>mybatis-plus-generator</artifactId>
  30. <version>3.1.0</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-freemarker</artifactId>
  35. <version>2.1.4.RELEASE</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.freemarker</groupId>
  39. <artifactId>freemarker</artifactId>
  40. <!--<version>2.3.20</version>-->
  41. <version>2.3.27-incubating</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>mysql</groupId>
  45. <artifactId>mysql-connector-java</artifactId>
  46. <scope>runtime</scope>
  47. </dependency>
  48. </dependencies>
  49. <build>
  50. <plugins>
  51. <plugin>
  52. <groupId>org.springframework.boot</groupId>
  53. <artifactId>spring-boot-maven-plugin</artifactId>
  54. </plugin>
  55. </plugins>
  56. </build>
  57. </project>

App.java

  1. package com.test.invoice;
  2. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  3. import com.baomidou.mybatisplus.generator.AutoGenerator;
  4. import com.baomidou.mybatisplus.generator.InjectionConfig;
  5. import com.baomidou.mybatisplus.generator.config.*;
  6. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  7. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  8. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  9. import org.apache.commons.lang.StringUtils;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.Scanner;
  13. /**
  14. * 代码生成类
  15. *
  16. * @author:
  17. * @version:
  18. * @date: 2019-10-15 19:43
  19. */
  20. public class App {
  21. /*
  22. 代码生成路径
  23. */
  24. private static final String outdir="D:\\finance-generator-framework-code\\";
  25. /**
  26. * <p>
  27. * 读取控制台内容
  28. * </p>
  29. */
  30. public static String scanner(String tip) {
  31. Scanner scanner = new Scanner(System.in);
  32. StringBuilder help = new StringBuilder();
  33. help.append("请输入" + tip + ":");
  34. System.out.println(help.toString());
  35. if (scanner.hasNext()) {
  36. String ipt = scanner.next();
  37. if (StringUtils.isNotEmpty(ipt)) {
  38. return ipt;
  39. }
  40. }
  41. throw new RuntimeException("请输入正确的" + tip + "!");
  42. }
  43. /**
  44. * RUN THIS
  45. */
  46. public static void main(String[] args) {
  47. // 代码生成器
  48. AutoGenerator mpg = new AutoGenerator();
  49. // 全局配置
  50. GlobalConfig gc = new GlobalConfig();
  51. //String projectPath = System.getProperty("user.dir");
  52. //gc.setOutputDir(projectPath + "/finance-generator-exp/src/main/java");
  53. gc.setOutputDir(outdir);
  54. gc.setAuthor("luoma");//作者
  55. gc.setOpen(false);
  56. gc.setBaseResultMap(true);
  57. gc.setBaseColumnList(true);
  58. gc.setMapperName("%sRepository");
  59. gc.setServiceName("I%sService");
  60. gc.setEntityName("%sEntity");
  61. gc.setEnableCache(false);
  62. gc.setFileOverride(true);
  63. mpg.setGlobalConfig(gc);
  64. // 数据源配置
  65. DataSourceConfig dsc = new DataSourceConfig();
  66. dsc.setUrl("jdbc:mysql://localhost:3306/luoma_test?useUnicode=true&useSSL=false&characterEncoding=utf8");
  67. // dsc.setSchemaName("public");
  68. dsc.setDriverName("com.mysql.jdbc.Driver");
  69. dsc.setUsername("root");
  70. dsc.setPassword("123456");
  71. mpg.setDataSource(dsc);
  72. // 包配置
  73. PackageConfig pc = new PackageConfig();
  74. pc.setModuleName(scanner("模块名"));
  75. pc.setParent("com.test");
  76. mpg.setPackageInfo(pc);
  77. // 自定义配置
  78. InjectionConfig cfg = new InjectionConfig() {
  79. @Override
  80. public void initMap() {
  81. // to do nothing
  82. }
  83. };
  84. List<FileOutConfig> focList = new ArrayList<>();
  85. focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
  86. @Override
  87. public String outputFile(TableInfo tableInfo) {
  88. // 自定义输入文件名称
  89. /* return projectPath + "/finance-generator-exp/src/main/resources/mapper/" + pc.getModuleName()
  90. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;*/
  91. return outdir +"com/test/invoice/"+pc.getModuleName()+"/mapper"
  92. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  93. }
  94. });
  95. cfg.setFileOutConfigList(focList);
  96. mpg.setCfg(cfg);
  97. mpg.setTemplate(new TemplateConfig().setXml(null));
  98. // 策略配置
  99. StrategyConfig strategy = new StrategyConfig();
  100. strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
  101. strategy.setColumnNaming(NamingStrategy.underline_to_camel);//字段名生成策略
  102. strategy.setSuperEntityClass("com.test.invoice.model.base.SuperEntity");// 自定义实体父类
  103. strategy.setEntityLombokModel(true);
  104. strategy.setInclude(scanner("表名")); // 需要生成的表
  105. strategy.setSuperEntityColumns("id");// 自定义实体,公共字段
  106. strategy.setControllerMappingHyphenStyle(true);
  107. strategy.setTablePrefix(pc.getModuleName() + "_");// 表前缀
  108. strategy.setRestControllerStyle(true);
  109. mpg.setStrategy(strategy);
  110. // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
  111. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  112. mpg.execute();
  113. }
  114. }

测试

1.运行 App main()

2.输入模块名称和表名称

  1. "D:\Program Files\Java\jdk1.8.0_151\bin\java.exe"
  2. 请输入模块名:
  3. invoice
  4. 请输入表名:
  5. t_rbt_test
  6. 20:23:40.415 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
  7. 20:23:41.411 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [D:\finance-generator-framework-code\com\test\invoice\entity]
  8. 20:23:41.425 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [D:\finance-generator-framework-code\com\test\invoice\controller]
  9. 20:23:41.426 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [D:\finance-generator-framework-code\com\test\invoice\service]
  10. 20:23:41.426 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [D:\finance-generator-framework-code\com\test\invoice\mapper]
  11. 20:23:41.426 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [D:\finance-generator-framework-code\com\test\invoice\service\impl]
  12. 20:23:41.524 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/mapper.xml.ftl; 文件:D:\finance-generator-framework-code\com/test/invoice/invoice/mapper/TRbtTestEntityMapper.xml
  13. 20:23:41.615 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/entity.java.ftl; 文件:D:\finance-generator-framework-code\com\test\invoice\entity\TRbtTestEntity.java
  14. 20:23:41.620 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/mapper.java.ftl; 文件:D:\finance-generator-framework-code\com\test\invoice\mapper\TRbtTestRepository.java
  15. 20:23:41.625 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/service.java.ftl; 文件:D:\finance-generator-framework-code\com\test\invoice\service\ITRbtTestService.java
  16. 20:23:41.635 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/serviceImpl.java.ftl; 文件:D:\finance-generator-framework-code\com\test\invoice\service\impl\TRbtTestServiceImpl.java
  17. 20:23:41.640 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/controller.java.ftl; 文件:D:\finance-generator-framework-code\com\test\invoice\controller\TRbtTestController.java
  18. 20:23:41.640 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================
  19. 进程已结束,退出代码 0

3.查看生成的文件

D:\finance-generator-framework-code\com\test\invoice

(1)TRbtTestController.java

D:\finance-generator-framework-code\com\test\invoice\controller

  1. package com.test.invoice.controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. /**
  5. * <p>
  6. * 前端控制器
  7. * </p>
  8. *
  9. * @author luoma
  10. * @since 2019-10-15
  11. */
  12. @RestController
  13. @RequestMapping("/invoice/t-rbt-test-entity")
  14. public class TRbtTestController {
  15. }

(2)TRbtTestEntity.java

D:\finance-generator-framework-code\com\test\invoice\entity

  1. package com.test.invoice.entity;
  2. import com.baomidou.mybatisplus.annotation.TableName;
  3. import java.time.LocalDateTime;
  4. import com.test.invoice.model.base.SuperEntity;
  5. import lombok.Data;
  6. import lombok.EqualsAndHashCode;
  7. import lombok.experimental.Accessors;
  8. /**
  9. * <p>
  10. *
  11. * </p>
  12. *
  13. * @author luoma
  14. * @since 2019-10-15
  15. */
  16. @Data
  17. @EqualsAndHashCode(callSuper = true)
  18. @Accessors(chain = true)
  19. @TableName("t_rbt_test")
  20. public class TRbtTestEntity extends SuperEntity {
  21. private static final long serialVersionUID = 1L;
  22. /**
  23. * 名称
  24. */
  25. private String name;
  26. /**
  27. * 版本号
  28. */
  29. private String version;
  30. /**
  31. * 创建人
  32. */
  33. private String createBy;
  34. /**
  35. * 创建时间
  36. */
  37. private LocalDateTime createTime;
  38. /**
  39. * 修改人
  40. */
  41. private String updateBy;
  42. /**
  43. * 修改时间
  44. */
  45. private LocalDateTime updateTime;
  46. /**
  47. * 是否删除
  48. */
  49. private Integer isDelete;
  50. /**
  51. * 系统时间戳
  52. */
  53. private LocalDateTime bizTime;
  54. }

(3)ITRbtTestService.java

D:\finance-generator-framework-code\com\test\invoice\service

  1. package com.test.invoice.service;
  2. import com.test.invoice.entity.TRbtTestEntity;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * <p>
  6. * 服务类
  7. * </p>
  8. *
  9. * @author luoma
  10. * @since 2019-10-15
  11. */
  12. public interface ITRbtTestService extends IService<TRbtTestEntity> {
  13. }

(4)TRbtTestServiceImpl.java

D:\finance-generator-framework-code\com\test\invoice\service\impl

  1. package com.test.invoice.service.impl;
  2. import com.test.invoice.entity.TRbtTestEntity;
  3. import com.test.invoice.mapper.TRbtTestRepository;
  4. import com.test.invoice.service.ITRbtTestService;
  5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * <p>
  9. * 服务实现类
  10. * </p>
  11. *
  12. * @author luoma
  13. * @since 2019-10-15
  14. */
  15. @Service
  16. public class TRbtTestServiceImpl extends ServiceImpl<TRbtTestRepository, TRbtTestEntity> implements ITRbtTestService {
  17. }

(5)TRbtTestRepository.java

D:\finance-generator-framework-code\com\test\invoice\mapper

  1. package com.test.invoice.mapper;
  2. import com.test.invoice.entity.TRbtTestEntity;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. /**
  5. * <p>
  6. * Mapper 接口
  7. * </p>
  8. *
  9. * @author luoma
  10. * @since 2019-10-15
  11. */
  12. public interface TRbtTestRepository extends BaseMapper<TRbtTestEntity> {
  13. }

(6)TRbtTestEntityMapper.xml

D:\finance-generator-framework-code\com\test\invoice\invoice\mapper

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.test.invoice.mapper.TRbtTestRepository">
  4. <!-- 通用查询映射结果 -->
  5. <resultMap id="BaseResultMap" type="com.test.invoice.entity.TRbtTestEntity">
  6. <result column="id" property="id" />
  7. <result column="name" property="name" />
  8. <result column="version" property="version" />
  9. <result column="create_by" property="createBy" />
  10. <result column="create_time" property="createTime" />
  11. <result column="update_by" property="updateBy" />
  12. <result column="update_time" property="updateTime" />
  13. <result column="is_delete" property="isDelete" />
  14. <result column="biz_time" property="bizTime" />
  15. </resultMap>
  16. <!-- 通用查询结果列 -->
  17. <sql id="Base_Column_List">
  18. id,
  19. name, version, create_by, create_time, update_by, update_time, is_delete, biz_time
  20. </sql>
  21. </mapper>

mybatis-generator 插件使用

安装插件

Database 工具操作

连接数据库

这里我连接的是 Oracle

属性 描述
名称 根据业务情况起一个易记的名称
主机 数据库 IP 地址
端口 数据库端口号
SID 服务名称,TNS 中的 SERVICE_NAME
用户 用户名
密码 密码
url jdbc:oracle:thin:@IP:端口号:服务名

找到对应的表,右键 mybatis-generator

选择对应选项

对应目录下生成了代码

Mybatis X 插件

https://baomidou.com/guides/mybatis-x/
MybatisX 是一款专为 IntelliJ IDEA 设计的快速开发插件,旨在提升 MyBatis 与 MyBatis-Plus 框架的开发效率。

IDEA DB 连接 Oracle 错误总结

ORA-12505, TNS:listener does not currently know of SID

参考:idea链接oracle数据库报错:[66000][12505] Listener refused the connection with the following error:

错误描述

  1. [66000][12505] Listener refused the connection with the following error: ORA-12505, TNS:listener does not currently know of SID given in connect descriptor (CONNECTION_ID=Bn8THbnmRYmuHin4mmnWzw==) oracle.net.ns.NetException: Listener refused the connection with the following error: ORA-12505, TNS:listener does not currently know of SID given in connect descriptor (CONNECTION_ID=Bn8THbnmRYmuHin4mmnWzw==).

查询 sid

  1. select INSTANCE_NAME from v$instance;

上图中 SID 选项替换为查询结果即可

ORA-01005: 给出空口令; 登录被拒绝

问题描述

  1. [72000][1005] ORA-01005: 给出空口令; 登录被拒绝

找了半天,妈的原来是密码输入错误了导致的,输入正确的密码即可