关于直接main方法运行生成代码可参考我的这篇文章:MP实战系列(六)之代码生成器讲解
在线配置主要参考jeesite和jeecg,gun等开源项目,但是与它们相比又有很多不同?
与jeesite相比,jeesite采用的自己重新改装的MyBatis和使用freemarker模板进行在线代码配置生成;与jeecg相比,jeecg的持久层叫minidao,该dao按照其官方文档所说,即具有Hibernate的全自动性,又兼有MyBatis的灵活性。与gun相比,gun的与我该在线配置代码生成器,比较相似,但总的来说,并不一样。
关于jeesite开源地址可以参考该网址:https://gitee.com/thinkgem/jeesite4
关于jeecg开源地址可以参考该网址:https://gitee.com/jeecg
我的关于EasyPoi导出Excel和EasyPoi以Excel格式批量录入数据,均采用jeecg的开源项目EasyPoi。
gun的话,我之所以与其不一样,是因为其代码生成器以zip包形式生成相关表代码。而我直接就是在页面上输入路径,直接在本地生成,当然了,生成以后还不能直接用,需要导入本地,但是总的来说,改动几乎为零,与之前我所提到过的MyBatis的逆向工程对比而言。
当然了,也不能完全否定MyBatis的逆向工程,毕竟只要项目结构和架构设计妥当还是很有效率的。
关于MyBatis的逆向工程可以参考我的这两篇博文:
动态web项目的逆向工程地址为:mybatis逆向工程之动态web项目
Maven工程的逆向工程地址为:mybatis逆向工程之maven工程
在线配置代码生成主要是为了提高研发人员的工作效率。之前我就强调过,DRY原则的重要性,并为此写了这篇文章编程之代码抽象三原则,大家可以借鉴和参考。
下面开始进入正题讲解在线配置代码生成器的思路:
首先准备环境:JDK8+MAVEN3+Eclipse或IDEA+Spring+MyBatis Plus+SpringMVC
一、导入MAVEN依赖
以下依赖,是我公司中几个项目比较通用的依赖,大家可以直接导入进来即可。当然了,建议阿里云私服,因为在maven公共仓库下载如下依赖,对于网速具有一定的要求,记得之前研究某个开源技术是,光下载依赖就耽误我不少时间,而且有的时候因为本地仓库依赖冲突问题或者其他意外问题使对应的开源项目暂时无法运行起来。
关于线上私服搭建可以参考我的这篇文章:Maven搭建私服
<properties> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding> <maven.compiler.encoding>UTF-8maven.compiler.encoding> <spring.version>4.3.13.RELEASEspring.version> <junit.version>4.12junit.version> <druid.version>1.1.0druid.version> <fastjson.version>1.2.8fastjson.version> <mybaitsplus.version>2.1.8mybaitsplus.version> <mysql.version>5.1.38mysql.version> <log4j.version>1.2.17log4j.version> <slf4j.version>1.7.19slf4j.version> <aspectjweaver.version>1.8.8aspectjweaver.version> <fileupload.version>1.3.1fileupload.version> <jstl.version>1.2jstl.version> <commons-io.version>2.5commons-io.version> <commons-fileupload.version>1.3.1commons-fileupload.version> <ruedigermoeller-fst.version>2.56ruedigermoeller-fst.version> <json.version>20170516json.version> <dozer.version>5.5.1dozer.version> <runtime.version>7.0.0.Finalruntime.version> properties> <dependencies> <dependency> <groupId>redis.clientsgroupId> <artifactId>jedisartifactId> <version>2.1.0version> dependency> <dependency> <groupId>org.springframework.datagroupId> <artifactId>spring-data-redisartifactId> <version>1.0.2.RELEASEversion> dependency> <dependency> <groupId>org.mybatis.cachesgroupId> <artifactId>mybatis-ehcacheartifactId> <version>1.0.3version> dependency> <dependency> <groupId>org.kiegroupId> <artifactId>kie-apiartifactId> <version>${runtime.version}version> dependency> <dependency> <groupId>org.droolsgroupId> <artifactId>drools-coreartifactId> <version>${runtime.version}version> dependency> <dependency> <groupId>org.droolsgroupId> <artifactId>drools-decisiontablesartifactId> <version>${runtime.version}version> dependency> <dependency> <groupId>org.jbpmgroupId> <artifactId>jbpm-testartifactId> <version>${runtime.version}version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>${junit.version}version> <scope>testscope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-context-supportartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring.version}version> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aopartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-beansartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring.version}version> <type>jartype> <scope>compilescope> dependency> <dependency> <groupId>org.aspectjgroupId> <artifactId>aspectjweaverartifactId> <version>${aspectjweaver.version}version> dependency> <dependency> <groupId>commons-fileuploadgroupId> <artifactId>commons-fileuploadartifactId> <version>${fileupload.version}version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>jstlartifactId> <version>${jstl.version}version> dependency> <dependency> <groupId>com.baomidougroupId> <artifactId>mybatis-plusartifactId> <version>${mybaitsplus.version}version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>${mysql.version}version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>${druid.version}version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>fastjsonartifactId> <version>${fastjson.version}version> dependency> <dependency> <groupId>log4jgroupId> <artifactId>log4jartifactId> <version>${log4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-apiartifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-log4j12artifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>org.apache.commonsgroupId> <artifactId>commons-lang3artifactId> <version>3.3.2version> dependency> <dependency> <groupId>commons-iogroupId> <artifactId>commons-ioartifactId> <version>${commons-io.version}version> dependency> <dependency> <groupId>de.ruedigermoellergroupId> <artifactId>fstartifactId> <version>${ruedigermoeller-fst.version}version> dependency> <dependency> <groupId>commons-codecgroupId> <artifactId>commons-codecartifactId> <version>1.10version> dependency> <dependency> <groupId>commons-beanutilsgroupId> <artifactId>commons-beanutilsartifactId> <version>1.9.3version> dependency> <dependency> <groupId>org.jsongroupId> <artifactId>jsonartifactId> <version>20170516version> dependency> <dependency> <groupId>org.apache.commonsgroupId> <artifactId>commons-emailartifactId> <version>1.4version> dependency> <dependency> <groupId>javax.activationgroupId> <artifactId>activationartifactId> <version>1.1.1version> dependency> <dependency> <groupId>com.google.zxinggroupId> <artifactId>coreartifactId> <version>3.3.0version> dependency> <dependency> <groupId>com.google.zxinggroupId> <artifactId>javaseartifactId> <version>3.3.0version> dependency> <dependency> <groupId>eu.bitwalkergroupId> <artifactId>UserAgentUtilsartifactId> <version>1.20version> dependency> <dependency> <groupId>org.apache.httpcomponentsgroupId> <artifactId>httpclientartifactId> <version>4.5.3version> dependency> <dependency> <groupId>org.jsoupgroupId> <artifactId>jsoupartifactId> <version>1.9.1version> dependency> <dependency> <groupId>com.drewnoakesgroupId> <artifactId>metadata-extractorartifactId> <version>2.9.1version> dependency> <dependency> <groupId>net.coobirdgroupId> <artifactId>thumbnailatorartifactId> <version>0.4.8version> dependency> <dependency> <groupId>com.bladejavagroupId> <artifactId>blade-patchcaartifactId> <version>1.0.5version> dependency> <dependency> <groupId>com.fasterxml.jackson.coregroupId> <artifactId>jackson-coreartifactId> <version>2.9.4version> dependency> <dependency> <groupId>com.fasterxml.jackson.coregroupId> <artifactId>jackson-databindartifactId> <version>2.9.5version> dependency> <dependency> <groupId>com.fasterxml.jackson.dataformatgroupId> <artifactId>jackson-dataformat-xmlartifactId> <version>2.9.5version> dependency> <dependency> <groupId>dom4jgroupId> <artifactId>dom4jartifactId> <version>1.6.1version> dependency> <dependency> <groupId>jaxengroupId> <artifactId>jaxenartifactId> <version>1.1.6version> dependency> <dependency> <groupId>org.yamlgroupId> <artifactId>snakeyamlartifactId> <version>1.17version> dependency> <dependency> <groupId>net.sf.dozergroupId> <artifactId>dozerartifactId> <version>${dozer.version}version> dependency> <dependency> <groupId>com.belerwebgroupId> <artifactId>pinyin4jartifactId> <version>2.5.0version> dependency> <dependency> <groupId>org.apache.antgroupId> <artifactId>antartifactId> <version>1.9.7version> dependency> <dependency> <groupId>net.sf.jmimemagicgroupId> <artifactId>jmimemagicartifactId> <version>0.1.3version> <exclusions> <exclusion> <groupId>xercesgroupId> <artifactId>xercesImplartifactId> exclusion> <exclusion> <groupId>org.codehaus.jacksongroupId> <artifactId>jackson-xcartifactId> exclusion> <exclusion> <groupId>org.codehaus.jacksongroupId> <artifactId>jackson-jaxrsartifactId> exclusion> <exclusion> <artifactId>log4jartifactId> <groupId>log4jgroupId> exclusion> exclusions> dependency> <dependency> <groupId>com.qcloudgroupId> <artifactId>cos_apiartifactId> <version>5.2.4version> dependency> <dependency> <groupId>commons-codecgroupId> <artifactId>commons-codecartifactId> <version>1.11version> dependency> <dependency> <groupId>com.squareup.okhttp3groupId> <artifactId>okhttpartifactId> <version>3.9.1version> dependency> <dependency> <groupId>com.squareup.okiogroupId> <artifactId>okioartifactId> <version>1.13.0version> dependency> <dependency> <groupId>org.mindrotgroupId> <artifactId>jbcryptartifactId> <version>0.4version> dependency> <dependency> <groupId>cn.afterturngroupId> <artifactId>easypoi-baseartifactId> <version>3.1.0version> dependency> <dependency> <groupId>cn.afterturngroupId> <artifactId>easypoi-webartifactId> <version>3.1.0version> dependency> <dependency> <groupId>cn.afterturngroupId> <artifactId>easypoi-annotationartifactId> <version>3.1.0version> dependency> <dependency> <groupId>cn.hutoolgroupId> <artifactId>hutool-allartifactId> <version>4.1.0version> dependency> <dependency> <groupId>com.mangofactorygroupId> <artifactId>swagger-springmvcartifactId> <version>1.0.2version> dependency> <dependency> <groupId>com.mangofactorygroupId> <artifactId>swagger-modelsartifactId> <version>1.0.2version> dependency> <dependency> <groupId>com.wordnikgroupId> <artifactId>swagger-annotationsartifactId> <version>1.3.11version> dependency> <dependency> <groupId>com.google.guavagroupId> <artifactId>guavaartifactId> <version>15.0version> dependency> <dependency> <groupId>io.springfoxgroupId> <artifactId>springfox-swagger2artifactId> <version>2.7.0version> dependency> <dependency> <groupId>io.springfoxgroupId> <artifactId>springfox-swagger-uiartifactId> <version>2.7.0version> dependency> <dependency> <groupId>net.sf.ehcachegroupId> <artifactId>ehcache-coreartifactId> <version>2.6.6version> dependency> <dependency> <groupId>javax.servlet.jspgroupId> <artifactId>jsp-apiartifactId> <version>2.1version> <scope>compilescope> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>javax.servlet-apiartifactId> <version>3.1.0version> <scope>compilescope> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-coreartifactId> <version>1.4.0version> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-webartifactId> <version>1.4.0version> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-springartifactId> <version>1.4.0version> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-ehcacheartifactId> <version>1.4.0version> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-quartzartifactId> <version>1.4.0version> dependency> <dependency> <groupId>com.gexin.platformgroupId> <artifactId>gexin-rp-sdk-httpartifactId> <version>4.0.1.17version> dependency> <dependency> <groupId>org.apache.velocitygroupId> <artifactId>velocityartifactId> <version>1.6.4version> dependency>
二、导入正确的依赖后,即可编写对应的Controller方法
关于@ApiOperation注解主要是为了接口文档自动化,传统的编写word文档作为接口管理,耗时效率低,使用swagger或者swagger2在线可以直接测试,又方便安卓或者web研发人员管理和测试
关于swagger接口自动化搭建可以参考我的这几篇文章:
MP实战系列(八)之SpringBoot+Swagger2
MP实战系列(十)之SpringMVC集成SpringFox+Swagger2
SpringMVC+Swagger详细整合
这几篇文章我相信应该可以减少走弯路的可能性。
关于JSONObject,这里使用的是Hutool开源项目,该开源项目之前我也介绍过,集成Java研发常用工具类。
参考文档地址为:http://hutool.mydoc.io/
/** * 代码生成器接口 * @param author * @param dir * @param tableName * @return */ @PostMapping(value="/productCode",produces="application/json;charset=utf-8") @ApiOperation(value="代码生成器接口",httpMethod="POST",notes="代码生成器接口") public JSONObject productCode(String author,String dir,String tableName) { JSONObject json = new JSONObject(); try { if(!StrUtil.hasEmpty(author,dir,tableName)) { // 自定义需要填充的字段 ListtableFillList = new ArrayList<>(); tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE)); // 代码生成器 AutoGenerator mpg = new AutoGenerator().setGlobalConfig( // 全局配置 new GlobalConfig() .setOutputDir(dir)//输出目录 .setFileOverride(true)// 是否覆盖文件 .setActiveRecord(true)// 开启 activeRecord 模式 .setEnableCache(false)// XML 二级缓存 .setBaseResultMap(true)// XML ResultMap .setBaseColumnList(true)// XML columList .setAuthor(author) // 自定义文件命名,注意 %s 会自动填充表实体属性! .setMapperName("%sDao") .setXmlName("%sDao") .setServiceName("%sService") .setServiceImplName("%sServiceImpl") .setControllerName("%sController") ).setDataSource( // 数据源配置 new DataSourceConfig() .setDbType(DbType.MYSQL)// 数据库类型 .setTypeConvert(new MySqlTypeConvert() { // 自定义数据库表字段类型转换【可选】 @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("转换类型:" + fieldType); return super.processTypeConvert(fieldType); } }) .setDriverName("com.mysql.jdbc.Driver") .setUsername("root") .setPassword("1234") .setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false") ).setStrategy( // 策略配置 new StrategyConfig() .setTablePrefix(new String[]{"rms","js"})/// 此处可以修改为您的表前缀 .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略 .setInclude(new String[] {tableName}) // 需要生成的表 .setTableFillList(tableFillList) ).setPackageInfo( // 包配置 new PackageConfig() .setParent("com.blog")// 自定义包路径 .setController("controller")// 这里是控制器包名,默认 web ).setCfg( // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值 new InjectionConfig() { @Override public void initMap() { Map map = new HashMap<>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + ""); this.setMap(map); } }.setFileOutConfigList(Collections. singletonList(new FileOutConfig("/templates/mapper.xml.vm") { // 自定义输出文件目录 @Override public String outputFile(TableInfo tableInfo) { return dir+"//"+ tableInfo.getEntityName()+"Dao" + ".xml"; } })) ).setTemplate( // 关闭默认 xml 生成,调整生成 至 根目录 new TemplateConfig().setXml(null) ); // 执行生成 mpg.execute(); // 打印注入设置,这里演示模板里面怎么获取注入内容【可无】 System.err.println(mpg.getCfg().getMap().get("abc")); json.put("returnMsg", "代码生成成功"); json.put("returnCode", "000000"); }else { json.put("returnMsg", "参数异常"); json.put("returnCode", "111111"); } } catch (Exception e) { e.printStackTrace(); json.put("returnMsg", "代码生成失败"); json.put("returnCode", "222222"); } return json; }
三、界面
让大家看看效果:
有一点需要明确的是,该代码在线配置生成,只能针对本地window系统,如果已经部署到线上是无法生成的,也不会报错,因为window的文件系统和linux的文件系统存在差异。
当然了,这里的差异也不影响我们研发人员的正常使用。
该在线代码生成器的意义在于,每当用户提出一个新的需求时,我们总能快速生成相关的代码,然后专注于复杂的业务。简单的增删改查,谁都会。但是复杂的业务逻辑,就不仅仅谁都会了,虽然在网上看不少朋友说,重复的业务代码写久了也没意思。其实怎么说呢?我看过不少业务代码,发现一点,我和我的同学们都发现了这点,那就是许多业务代码基本就是复制粘贴的作品,甚至将代码上开发者名字都复制下来的,我想说,老兄你也太懒了吧。
当然了,复制粘贴是可以提高效率,但是好歹也得代码格式化下,让代码看起来工整,还有就是有些注释该加还是要加,当然注释越少越好,真正优秀的代码,是让人一看就明白是什么意思,所以说那些自以为是的人,自以为自己代码写的让人看不懂就自我感觉非常牛逼,其实那样只会让你越来越退步,直到失业。所以说,代码就好比讲通俗易懂的故事,至少要让人家在最短的时间看懂,而不是光看你这个代码我就花了一天,到最好我只有重构了这样的不是办法中的办法。
关于web界面上展示MySQL所有数据库信息,单个数据库所有表信息,数据表所有字段信息,大家可以参考我编写的如下DAO:
public interface DataBaseDao {
@Select("SHOW DATABASES")
public List
xml文件:
这里我采用的是MyBatis的注解,当然这种注解的最不好缺点就是使Java代码和sql混合一起显得杂乱,当然少的时候看起来没什么,多的话,建议使用xml方式,这也是MyBatis官方比较推崇的方式。
补充说明:使用MyBatis的注解还是得存在对应的xml文件,尽管你的xml文件没有对应的sql。
DataBaseService代码和实现类如下:
Service代码:
public interface DataBaseService { public List> selectDataBases(); public List > showTables(@Param("databaseName")String databaseName); public List > showColumns(@Param("tableName")String tableName); }
Service实现类:
@Service public class DataBaseServiceImpl implements DataBaseService { @Autowired private DataBaseDao dataBaseDao; @Override public List> selectDataBases() { // TODO Auto-generated method stub return dataBaseDao.selectDataBases(); } @Override public List > showTables(String databaseName) { // TODO Auto-generated method stub return dataBaseDao.showTables(databaseName); } @Override public List > showColumns(String tableName) { // TODO Auto-generated method stub return dataBaseDao.showColumns(tableName); } }
对应的Controller如下:
/** * 获取所有数据库 * @return */ @GetMapping(value="/getAllDataBaseInfo",produces="application/json;charset=utf-8") @ApiOperation(value="获取所有数据库",httpMethod="GET",notes="获取所有数据库") public JSONObject getAllDataBaseInfo() { JSONObject json = new JSONObject(); try { List> list = dataBaseService.selectDataBases(); if(list.size()!=0) { json.put("lines", list.size()); json.put("list", list); json.put("returnMsg", "存在数据"); json.put("returnCode", "00000"); }else { json.put("returnMsg", "没有数据"); json.put("returnCode", "111111"); } } catch (Exception e) { e.printStackTrace(); json.put("returnMsg", "特殊异常"); json.put("returnCode", "222222");// TODO: handle exception } return json; } /** * 获取单个数据库所有表信息 * @param databaseName * @return */ @GetMapping(value="/querySingleDataBaseInfo",produces="application/json;charset=utf-8") @ApiOperation(value="获取单个数据库所有表信息",httpMethod="GET",notes="获取单个数据库所有表信息") public JSONObject querySingleDataBaseInfo(String databaseName) { JSONObject json = new JSONObject(); try { if(!StrUtil.isEmpty(databaseName)) { List > list = dataBaseService.showTables(databaseName); if(list.size()!=0) { json.put("lines", list.size()); json.put("list", list); json.put("returnMsg", "获取数据"); json.put("returnCode", "00000"); }else { json.put("returnMsg", "获取数据失败"); json.put("returnCode", "111111"); } }else { json.put("returnMsg", "参数异常"); json.put("returnCode", "222222"); } } catch (Exception e) { e.printStackTrace(); json.put("returnMsg", "特殊异常"); json.put("returnCode", "333333");// TODO: handle exception } return json; } /** * 获取单个表所有字段信息 * @param tableName * @return */ @GetMapping(value="/querySingleTableInfo",produces="application/json;charset=utf-8") @ApiOperation(value="获取单个表所有字段信息",httpMethod="GET",notes="获取单个数据库所有表信息") public JSONObject querySingleTableInfo(String tableName) { JSONObject json = new JSONObject(); try { if(!StrUtil.isEmpty(tableName)) { List > list = dataBaseService.showColumns(tableName); if(list.size()!=0) { json.put("lines", list.size()); json.put("list", list); json.put("returnMsg", "获取数据"); json.put("returnCode", "00000"); }else { json.put("returnMsg", "获取数据失败"); json.put("returnCode", "111111"); } }else { json.put("returnMsg", "参数异常"); json.put("returnCode", "222222"); } } catch (Exception e) { e.printStackTrace(); json.put("returnMsg", "特殊异常"); json.put("returnCode", "333333");// TODO: handle exception } return json; }
希望本篇文章能够给大家的开发效率带来提升