使用mybatis-plus逆向生成代码

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

首先加入所需的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>复制代码

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

1.配置数据源:

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

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

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.生成策略配置:

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

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

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文件配置:

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):

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();复制代码

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值