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

栏目: Java · 发布时间: 7年前

内容简介:在用Java写项目的过程中存在很多重复性的工作, 比如数据库层的编写,不止这些, 还有些前端页面也是, 这里分享一个Java编写的代码生成器

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

不止这些, 还有些前端页面也是, 这里分享一个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 可以选 mybatismybatis-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);
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Clean Architecture

Clean Architecture

Robert C. Martin / Prentice Hall / 2017-9-20 / USD 34.99

Practical Software Architecture Solutions from the Legendary Robert C. Martin (“Uncle Bob”) By applying universal rules of software architecture, you can dramatically improve developer producti......一起来看看 《Clean Architecture》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换