自定义Mybatis逆向工程Maven插件
2018-02-05 19:51
337 查看
我的一篇博客介绍了基于Java Config形式的Mybatis逆向工程,通过定义几个java变量,然后运行main方法可以执行逆向工程,这篇博客就是将那个工程改造成一个Maven插件。
开发Maven插件,首先需要创建一个Maven Plugin项目,我是基于IDEA开发的。IDEA如何创建Maven插件项目自行百度,这里就不说了。
创建好Mojo项目后,需要修改器Pom.xml文件,指定packaging类型为maven-plugin,同时添加开发插件的依赖:
@Mojo():定义插件目标,一个插件可以有多个目标,也就是有 多个@Mojo标识的AbstractMojo子类,绑定插件时可以自由选择将哪个目标绑定到Maven生命周期的某个阶段。
下一步你需要有一个类去继承AbstractMojo,重写其execute方法,插件在执行时会调用此方法,也就是说此方法是插件的入口。插件在启动时会实例化一个AbstractMojo的子类,具体实例化谁需要看@Mojo注解在哪层子类上,所以此处我定义了两个类直接或间接继承AbstractMojo,MybatisGeneratorConfig作为配置类,MybatisGenerator是实际执行逆向工程的工具类,MybatisGenerator 继承MybatisGeneratorConfig,将@Mojo标识在MybatisGenerator上。这样MybatisGenerator在执行execute方法时能够获取到MybatisGeneratorConfig里的配置信息。
还有一个类GeneralCommentGenerator和之前那篇博客的一样,就不列出来了,总共就是三个类。
我在MybatisGeneratorConfig类里的变量上标识了很多@Parameter注解,这些注解指定了插件在配置时能够传入哪些外部参数,Maven插件在启动时实例化@Mojo标识类的对象,同时将外部参数传入到此类(或父类)的属性中。@Parameter可以定义插件配置的形式,是否有默认值,是否仅可读,是否必须等等,若是必须的则在配置插件时必须有值。
以上就是插件的所有代码了,之后执行Maven的install命令,将插件安装到本地maven仓库。
下面就是在其他项目中使用整个插件。
首先需要在项目中引入自定义的maven插件:
我默认是在一台电脑上,刚刚已经将插件安装到了本地maven仓库,所以这里引用能够直接生效。
可以通过Ctrl+左键点击configuration内的配置,查看当前插件的可配置选项。
我们将逆向工程插件的mybatisGenerate目标绑定到了compile阶段,也就是说在执行maven compile生命周期时会触发此插件的相应目标。
![](https://img-blog.csdn.net/20180205194413071?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjc1Mjk5MTc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
插件配置在了project目录下的pom.xml里,逆向工程的数据库驱动包放在了project-root下,同时制定生成的Model,Mapper接口及Mapper.xml也指向project-root项目。生成的包的路径,数据库地址,用户名,密码等等信息我在插件里做了默认配置,需要的可以在< configuration>覆盖默认配置,同时若项目的结构和我的不相同,只要修改下插件里的默认配置就好了。自行看插件源码,很明了的。
在指定好要生成的数据库表之后,在IDEA里运行complie,就能执行逆向工程插件了,执行完之后务必将< goal>,否则每次编译都会执行此插件了。
开发Maven插件,首先需要创建一个Maven Plugin项目,我是基于IDEA开发的。IDEA如何创建Maven插件项目自行百度,这里就不说了。
创建好Mojo项目后,需要修改器Pom.xml文件,指定packaging类型为maven-plugin,同时添加开发插件的依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bob</groupId> <artifactId>plugin</artifactId> <version>1.0-SNAPSHOT</version> <packaging>maven-plugin</packaging> <properties> <maven.version>3.5.2</maven.version> <plugin-annotations.version>3.3</plugin-annotations.version> <mybatis-generator>1.3.5</mybatis-generator> </properties> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>${maven.version}</version> </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> <artifactId>maven-plugin-annotations</artifactId> <version>${plugin-annotations.version}</version> </dependency> <!-- Mybatis 逆向工程 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>${mybatis-generator}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
@Mojo():定义插件目标,一个插件可以有多个目标,也就是有 多个@Mojo标识的AbstractMojo子类,绑定插件时可以自由选择将哪个目标绑定到Maven生命周期的某个阶段。
下一步你需要有一个类去继承AbstractMojo,重写其execute方法,插件在执行时会调用此方法,也就是说此方法是插件的入口。插件在启动时会实例化一个AbstractMojo的子类,具体实例化谁需要看@Mojo注解在哪层子类上,所以此处我定义了两个类直接或间接继承AbstractMojo,MybatisGeneratorConfig作为配置类,MybatisGenerator是实际执行逆向工程的工具类,MybatisGenerator 继承MybatisGeneratorConfig,将@Mojo标识在MybatisGenerator上。这样MybatisGenerator在执行execute方法时能够获取到MybatisGeneratorConfig里的配置信息。
/** * Mybatis逆向工程解析器 * 基于Mybatis Generator 1.3.5 Release * * @author wb-jjb318191 * @create 2017-09-28 17:08 */ public abstract class MybatisGenerator extends AbstractMojo { /** * 指定要生成的Table */ @Parameter(required = true) protected List<String> tables; /** * 连接数据库驱动包,默认地址前缀是"targetModule"模块下的resources路径 */ @Parameter(defaultValue = "mysql-connector-java-5.1.44-bin.jar") protected String driverPath; /** * 指定生成java文件的编码格式 */ @Parameter(defaultValue = "UTF-8") protected String fileEncoding; /** * 指定JDBC信息 */ @Parameter(defaultValue = "com.mysql.jdbc.Driver") protected String driverClass; /** * 指定连接数据库的地址 */ @Parameter(defaultValue = "jdbc:mysql://localhost:3306/project") protected String connectionUrl; /** * 用户名 */ @Parameter(defaultValue = "root") protected S 10272 tring userName; /** * 密码 */ @Parameter(defaultValue = "lanboal") protected String password; /** * 指定项目根目录 */ @Parameter(property = "user.dir") private String projectRootPath; /** * 指定文件生成的模块 */ @Parameter(defaultValue = "") private String targetModule; /** * java根路径 */ @Parameter(defaultValue = "\\src\\main\\java") private String javaPath; /** * 资源根路径 */ @Parameter(defaultValue = "\\src\\main\\resources") private String resuorcesPath; /** * 指定Java Model生成位置 */ protected String javaModelTargetProject; /** * java实体类包名 */ @Parameter(defaultValue = "com.bob.project.mvc.entity.model") protected String javaModelPackage; /** * 指定Java DAO接口生成位置 */ protected String javaMapperTargetProject; /** * Mapper接口包名 */ @Parameter(defaultValue = "com.bob.project.mvc.mapper") protected String javaMapperPackage; /** * 指定Mapper.xml生成位置 */ protected String sqlmapTargetproject; /** * Mapper.xml文件路径 */ @Parameter(defaultValue = "com.bob.project.mvc.mapper", required = false) protected String sqlMapperPackage; /** * 初始化参数 */ protected void initParameter() { if (!"".equals(targetModule)) { targetModule = "\\" + targetModule; } String pathPrefix = projectRootPath + targetModule; javaModelTargetProject = pathPrefix + javaPath; javaMapperTargetProject = pathPrefix + javaPath; sqlmapTargetproject = pathPrefix + resuorcesPath; //获取驱动Jar包的路径,若不是本地地址,则加上项目前缀 if (!driverPath.contains(":")) { driverPath = sqlmapTargetproject + "\\" + driverPath; } } protected void printParameters() { System.out.println("打印逆向工程打印参数"); System.out.println("tables :" + tables.toString()); System.out.println("fileEncoding :" + fileEncoding.toString()); System.out.println("driverPath :" + driverPath.toString()); System.out.println("driverClass :" + driverClass.toString()); System.out.println("connectionUrl :" + connectionUrl.toString()); System.out.println("userName :" + userName.toString()); System.out.println("password :" + password.toString()); System.out.println("targetModule :" + targetModule.toString()); System.out.println("projectRootPath :" + projectRootPath.toString()); System.out.println("javaModelTargetProject :" + javaModelTargetProject.toString()); System.out.println("javaMapperTargetProject :" + javaMapperTargetProject.toString()); System.out.println("sqlmapTargetproject :" + sqlmapTargetproject.toString()); } } /** * Mybatis逆向工程基于Java形式的配置类 * * @author wb-jjb318191 * @create 2017-09-30 9:17 */ @Mojo(name = "mybatisGenerate") public class MybatisGenerator extends MybatisGeneratorConfig { @Override public void execute() throws MojoExecutionException, MojoFailureException { initParameter(); printParameters(); try { Configuration config = configMybatisGenerator(); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, new DefaultShellCallback(true), new ArrayList<String>()); myBatisGenerator.generate(null); } catch (Exception e) { System.out.println("逆向工程执行失败"); e.printStackTrace(); } } public Configuration configMybatisGenerator() { Configuration configuration = new Configuration(); configuration.addClasspathEntry(driverPath); Context context = new Context(null); context.setTargetRuntime("MyBatis3"); context.setId("wb-jjb318191"); context.addProperty("javaFileEncoding", fileEncoding); //设置注解生成器 context.setCommentGeneratorConfiguration(generateCommentConfiguration()); //设置JDBC连接配置 context.setJdbcConnectionConfiguration(generateJDBCConnectionConfiguration()); //设置JDBC Type 与Java Type之间的映射解析器 context.setJavaTypeResolverConfiguration(generateJavaTypeResolverConfiguration()); //设置Java Model生成配置 context.setJavaModelGeneratorConfiguration(generateJavaModelGeneratorConfiguration()); //设置DAO层的生成配置 context.setSqlMapGeneratorConfiguration(generateSqlMapGeneratorConfiguration()); //设置Mapper.xml生成 context.setJavaClientGeneratorConfiguration(generateJavaClientGeneratorConfiguration()); //设置需要生成的Table及生成形式 for (TableConfiguration tableConfiguration : generateTableConfigurations(context)) { context.addTableConfiguration(tableConfiguration); } configuration.addContext(context); return configuration; } /** * 配置注解生成器 * * @return */ private CommentGeneratorConfiguration generateCommentConfiguration() { CommentGeneratorConfiguration configuration = new CommentGeneratorConfiguration(); configuration.setConfigurationType(GeneralCommentGenerator.class.getName()); //是否去除自动生成的注释 true:是 : false:否 configuration.addProperty("suppressAllComments", "false"); configuration.addProperty("addRemarkComments", "true"); return configuration; } /** * 设置数据库连接的信息:驱动类、连接地址、用户名、密码 * * @return */ private JDBCConnectionConfiguration generateJDBCConnectionConfiguration() { JDBCConnectionConfiguration configuration = new JDBCConnectionConfiguration(); configuration.setDriverClass(driverClass); String jdbcSuffix = "?useUnicode=true&characterEncoding=UTF8&useSSL=false"; configuration.setConnectionURL(connectionUrl + jdbcSuffix); configuration.setUserId(userName); configuration.setPassword(password); return configuration; } /** * 设置JDBC Type 与Java Type之间的映射解析器 * * @return */ private JavaTypeResolverConfiguration generateJavaTypeResolverConfiguration() { JavaTypeResolverConfiguration configuration = new JavaTypeResolverConfiguration(); //可自定义类型映射解析器 configuration.setConfigurationType(null); //默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal configuration.addProperty("forceBigDecimals", "true"); return configuration; } /** * 配置Java Model生成 * * @return */ private JavaModelGeneratorConfiguration generateJavaModelGeneratorConfiguration() { JavaModelGeneratorConfiguration configuration = new JavaModelGeneratorConfiguration(); configuration.setTargetProject(javaModelTargetProject); configuration.setTargetPackage(javaModelPackage); //是否让schema作为包的后缀 configuration.addProperty("enableSubPackages", "false"); //从数据库返回的值被清理前后的空格 configuration.addProperty("trimStrings", "true"); return configuration; } /** * 配置Mapper.xml生成 * * @return */ private SqlMapGeneratorConfiguration generateSqlMapGeneratorConfiguration() { SqlMapGeneratorConfiguration configuration = new SqlMapGeneratorConfiguration(); configuration.setTargetProject(sqlmapTargetproject); configuration.setTargetPackage(sqlMapperPackage); //是否让schema作为包的后缀 configuration.addProperty("enableSubPackages", "false"); return configuration; } /** * 设置DAO生成 * * @return */ private JavaClientGeneratorConfiguration generateJavaClientGeneratorConfiguration() { JavaClientGeneratorConfiguration configuration = new JavaClientGeneratorConfiguration(); configuration.setConfigurationType("XMLMAPPER"); configuration.setTargetProject(javaMapperTargetProject); configuration.setTargetPackage(javaMapperPackage); //是否让schema作为包的后缀 configuration.addProperty("enableSubPackages", "false"); return configuration; } private List<TableConfiguration> generateTableConfigurations(Context context) { List<TableConfiguration> configurations = new ArrayList<TableConfiguration>(); for (Object table : tables) { TableConfiguration configuration = new TableConfiguration(context); configuration.setTableName((String)table); configuration.setSelectByExampleStatementEnabled(false); configuration.setDeleteByExampleStatementEnabled(false); configuration.setCountByExampleStatementEnabled(false); configuration.setUpdateByExampleStatementEnabled(false); configurations.add(configuration); } return configurations; } }
还有一个类GeneralCommentGenerator和之前那篇博客的一样,就不列出来了,总共就是三个类。
我在MybatisGeneratorConfig类里的变量上标识了很多@Parameter注解,这些注解指定了插件在配置时能够传入哪些外部参数,Maven插件在启动时实例化@Mojo标识类的对象,同时将外部参数传入到此类(或父类)的属性中。@Parameter可以定义插件配置的形式,是否有默认值,是否仅可读,是否必须等等,若是必须的则在配置插件时必须有值。
以上就是插件的所有代码了,之后执行Maven的install命令,将插件安装到本地maven仓库。
下面就是在其他项目中使用整个插件。
首先需要在项目中引入自定义的maven插件:
<plugins> <!--############## Maven依赖插件 ############## --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <groupId>com.bob</groupId> <artifactId>plugin</artifactId> <version>1.0-SNAPSHOT</version> <configuration> <tables> <table>bank_account</table> <table>emp</table> </tables> <targetModule>project-root</targetModule> </configuration> <executions> <execution> <id>generate</id> <phase>compile</phase> <goals> <goal>mybatisGenerate</goal> <!--执行完之后注释掉 --> </goals> </execution> </executions> </plugin> </plugins>
我默认是在一台电脑上,刚刚已经将插件安装到了本地maven仓库,所以这里引用能够直接生效。
可以通过Ctrl+左键点击configuration内的配置,查看当前插件的可配置选项。
我们将逆向工程插件的mybatisGenerate目标绑定到了compile阶段,也就是说在执行maven compile生命周期时会触发此插件的相应目标。
插件配置在了project目录下的pom.xml里,逆向工程的数据库驱动包放在了project-root下,同时制定生成的Model,Mapper接口及Mapper.xml也指向project-root项目。生成的包的路径,数据库地址,用户名,密码等等信息我在插件里做了默认配置,需要的可以在< configuration>覆盖默认配置,同时若项目的结构和我的不相同,只要修改下插件里的默认配置就好了。自行看插件源码,很明了的。
在指定好要生成的数据库表之后,在IDEA里运行complie,就能执行逆向工程插件了,执行完之后务必将< goal>,否则每次编译都会执行此插件了。
相关文章推荐
- mybatis-generator-maven-plugin 插件扩展 增加自定义方法
- maven+mybatis+mybatis-generator+sql server 2005自动生成代码,加上自定义分页插件和批量插入更新插件
- maven+mybatis-generator插件反向生成源代码
- maven 自定义插件开发
- 用maven插件自动生成mybatis代码
- maven插件--MyBatis自动生成代码
- 使用Maven插件来完成Mybatis逆向工程
- MyBatis学习总结(15)——定制Mybatis自动代码生成的maven插件
- maven-mybatis-generator插件
- 插件目标[置顶] Maven自定义绑定
- maven插件mybatis-generator生成代码配置
- 使用Maven插件生成MyBatis代码
- maven(18)-mybatis generator插件
- MyBatis自定义插件使用
- 编写自定义Maven2插件
- maven插件mybatis-generator生成代码配置
- MyBatis学习总结(15)——定制Mybatis自动代码生成的maven插件
- maven插件mybatis-generator自动生成
- mybatis-genarator 自定义插件
- 使用Maven的assembly插件实现自定义打包