1、背景
最近开发项目后端时,需要用到mybatis plus来实现DAO层的数据访问,需要频繁创建service、mapper、entity等类和接口,这些工作重复繁琐又没有技术含量,所以在网上找了相关的工具来实现一键生成controller、service、mapper、entity等类和接口,大大节省无意义时间。
2、描述
这里用到了AutoGenerator工具,可以根据表结构自动生成controller、service、mapper、entity等代码,也可以自定义生成哪些表对应的代码,同时可以过滤不存在的表名。
3、环境准备
idea集成开发环境、jdk、maven(可用idea自带的)、包含表结构的数据库(mysql、oracle、postgreSQL等)、目标后端项目
4、实现过程
step 1
引入相关依赖包:
<!-- mybatis-plus和springboot整合包 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!-- 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!-- 数据库驱动,根据自己需求安装相应的数据库驱动,本文用的是postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.4.2</version>
</dependency>
其他的可选依赖包:
<!-- 自动生成api文档工具 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<!-- beetl 模板依赖 -->
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>2.7.0</version>
</dependency>
<!-- velocity 模板依赖 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
step 2
在目标项目下新建一个带main方法的类,里面需要对AutoGenerator进行配置并执行生成代码。
源码分析
本次主要用到AutoGenerator类进行MP代码生成,该类的主要属性如下:
main方法需要做的就是分别配置好上面几个属性,并传入AutoGenerator对象,然后用AutoGenerator对象调用execute()方法开始生成代码即可。
dataSource:主要设置数据库链接信息;
strategy:设置表和属性关联策略;
packageInfo:设置controller、service、mapper等组件在生成后的保存路径;
globalConfig:全局设置,可以设置元数据信息和所生成类的命名风格;
templateEngine:设置所用的模板引擎,默认使用Velocity引擎(说实话,我没看出各个引擎的生成结果有什么区别…)。
因此我们只需要按需进行设置,就可以执行自动生成代码了,main方法中的AutoGenerator对象配置可以看文章结尾提供的demo源码
5、待解决
目前的AutoGenerator似乎无法识别数据库中的视图,即使将StrategyConfig.skipView设为true也无效果。
98、源码链接
99、参考资料
https://blog.csdn.net/weixin_43314519/article/details/109345296