在用Java写项目的过程中存在很多重复性的工作, 比如数据库层的编写, XML
、 Dao
、 Service
大多是重复的
不止这些, 还有些前端页面也是, 这里分享一个Java编写的代码生成器 mybatis-generator
虽然名字叫 mybatis
但是不限应用于 mybatis
中, 任何与数据库表对应的代码都可以
https://github.com/GitHub-Laziji/mybatis-generator
克隆下来后简单几步就可以使用, 里面自带了两个模版在 resources
下
mybatis
这个是根据 commons-mybatis
架构编写的 mybatis-default
这个生成的是简单的 mybatis
类, 不依赖其他包 如果模版不合适可以自己模仿其中的模版进行修改
里面已经包含了一个 example
的配置文件, 直接在这个基础上使用即可
若要创建更多的配置文件, 在 resources
下创建 application-${name}.yml
文件, ${name}
随意, 例如: application-example.yml
配置文件内容如下, 填入数据库配置, 以及生成代码的包名
模版文件映射用于自定义生成文件的包格式以及文件名
动态属性包含
{packageFilePath}
包文件路径 例如: com/xxx/xxx
{className}
类名 由表名改为驼峰命名法得来 {suffix}
类名后缀 DO或VO 一般按以下配置即可
现在项目中有两套模版 template.path
可以选 mybatis
或 mybatis-default
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: mybatis
mapping: |
Model.java.vm: main/java/{packageFilePath}/database/model/{className}.java
Query.java.vm: main/java/{packageFilePath}/database/query/{className}Query.java
Dao.java.vm: main/java/{packageFilePath}/database/dao/{className}.java
Service.java.vm: main/java/{packageFilePath}/database/service/{className}Service.java
Mapper.xml.vm: main/resources/mapper/{className}Mapper.xml
在test文件下创建测试类
@ActiveProfiles("example")
中填入刚才配置文件名的 name
tableNames
需要生成的表, 可以多个 zipPath
代码导出路径 运行测试方法即可
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() throws IOException {
String[] tableNames = new String[]{"example_table1", "example_table2"};
String zipPath = "/home/code.zip";
generatorService.generateZip(tableNames,zipPath);
}
}