Java代码生成器mybatis-generator的使用

在用Java写项目的过程中存在很多重复性的工作, 比如数据库层的编写, XMLDaoService 大多是重复的

不止这些, 还有些前端页面也是, 这里分享一个Java编写的代码生成器mybatis-generator 虽然名字叫mybatis 但是不限应用于mybatis中, 任何与数据库表对应的代码都可以

项目地址

https://github.com/GitHub-Laziji/mybatis-generator

欢迎贡献各种模版

使用

目前项目中包含两个模版在resources下, 如果模版不合适可以自己模仿其中的模版进行修改

  • mybatis2 是根据 commons-mybatis 通用Mapper编写的, 依赖commons-mybatis 2.0
  • mybatis-default 这个生成的是简单的mybatis实体类、Dao接口以及XML, 不依赖其他包

配置文件

resources下创建application-${name}.yml文件, ${name}随意, 例如: application-example.yml, 可创建多个

配置文件属性:

  • spring.datasource 填入自己的项目数据库相关配置
  • generator.package 项目包名
  • generator.template.mapping 用于自定义生成文件的包格式以及文件名
  • generator.template.path 表示模版文件的路径目前可以选mybatismybatis-default

generator.template.mapping中可选的动态属性包含:

  • {packagePath} 包文件路径 例如: com/xxx/xxx
  • {className} 类名 由表名使用驼峰命名法得来
  • {customClassName} 自定义类名 (若未指定自定义类名, 则就是类名)
  • {suffix} 类名后缀 DO或VO (根据是否为视图)

一般按以下配置即可, 也可以自行扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
spring:
datasource:
url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/xxxx?characterEncoding=utf-8
username: xxxxxx
password: xxxxxx

generator:
package: com.xxx.xxx
template:
path: mybatis2
mapping: |
Model.java.vm: main/java/{packagePath}/database/model/{customClassName}.java
Query.java.vm: main/java/{packagePath}/database/query/{customClassName}Query.java
Dao.java.vm: main/java/{packagePath}/database/dao/{customClassName}Dao.java
Service.java.vm: main/java/{packagePath}/database/service/{customClassName}Service.java

生成代码

在test文件下创建测试类

  • @ActiveProfiles("example")中填入刚才配置文件名的name
  • tableNames需要生成的表, 可以多个
  • zipPath 代码导出路径

调用generatorService.generateZip传入参数可以是表名数组String[]或者TableItem[]

运行测试方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package pg.laziji.generator;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import pg.laziji.generator.mybatis.GeneratorService;

import javax.annotation.Resource;
import java.io.IOException;

@ActiveProfiles("example")
@RunWith(SpringRunner.class)
@SpringBootTest
public class ExampleTest {

@Resource
private GeneratorService generatorService;

@Test
public void test(){
String zipPath = "/home/code.zip";

// String[] tableNames = new String[]{"table1","table2"};
// generatorService.generateZip(tableNames,zipPath);

TableItem[] tableItems = new TableItem[]{
new TableItem("table1", "TableA"),
new TableItem("table2", "TableB")
};
generatorService.generateZip(tableItems,zipPath);
}
}