使用mybatis-plus逆向生成代码

在掘金看过 @SnailClimb 《回顾一下MyBatis逆向工程——自动生成代码》,也尝试了一下,确实能生成,不过他是使用mybatis.generator来逆向生成的,并且好像mybatis.generator只能生成mapper和mapper xml文件,相似controller、entity、service就生成不了,这样咱们的工做量仍是挺大的,本身找了一些资料,查了mybatis-plus能够生成controller、service、entity这类,因此仍是比较全的,本身就写篇博客记录一下。
apache

首先加入所需的jar包(这里还使用到了velocity模板引擎):缓存

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus</artifactId>
	<version>2.1.8</version>
</dependency>
<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity-engine-core</artifactId>
	<version>2.0</version>
</dependency>复制代码

接下来就是逆向工程的主要代码了:bash

1.配置数据源:mybatis

DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName(DRIVER);
dsc.setUrl(DATA_URL);
dsc.setUsername(USERNAME);
dsc.setPassword(PASSWORD);复制代码

2.设置一些全局的配置:app

GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(ROOT_DIR);
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
gc.setAuthor(AUTHOR);
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");复制代码

3.生成策略配置:ide

StrategyConfig strategy = new StrategyConfig();
//strategy.setTablePrefix(new String[] { "SYS_" });// 此处能够修改成您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[] {"auth_role"}); // 须要生成的表复制代码

4.生成文件所在包配置:post

PackageConfig pc = new PackageConfig();
pc.setParent("com.yif");
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("entity");
pc.setMapper("dao");复制代码

5.xml文件配置:ui

InjectionConfig cfg = new InjectionConfig() {
    @Override
    public void initMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
        this.setMap(map);
    }
};
//xml生成路径
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
    @Override
    public String outputFile(TableInfo tableInfo) {
        return "src/main/resources/"+"/mybatis/tables/"+tableInfo.getEntityName()+"Mapper.xml";
    }
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);

// 关闭默认 xml 生成,调整生成 至 根目录
TemplateConfig tc = new TemplateConfig();
tc.setXml(null);复制代码

6.至此,咱们该配置的都已经配置好了,只要将这些配置放入自动生成类便可(AutoGenerator):this

AutoGenerator mpg = new AutoGenerator();
mpg.setDataSource(dsc);			//数据源配置
mpg.setGlobalConfig(gc);		//全局配置
mpg.setStrategy(strategy);		//生成策略配置
mpg.setPackageInfo(pc);			//包配置
mpg.setCfg(cfg);				//xml配置
mpg.setTemplate(tc);			//
// 执行生成
mpg.execute();复制代码

最后运行,便可生成一系列的无聊的代码。spa

相关文章
相关标签/搜索