Mybatis反向生成能夠採用mybatis-generator工具
工具的調用方式我選擇採用run-with-java 即便用java main函數調用,這種方式的有點是相比maven-plugin調用,省去了jdbc driver包定位的問題,同時方便添加自定義插件,本文就採用了自定義的註釋插件來獲取數據庫字段註釋,造成field註釋。
同時引入的公用插件有java
pom.xmlmysql
<!--mybatis反向生成--> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <!--反向生成自動swagger註釋 --> <dependency> <groupId>com.github.misterchangray.mybatis.generator.plugins</groupId> <artifactId>myBatisGeneratorPlugins</artifactId> <version>1.2</version> </dependency> <!--反向生成加強插件--> <dependency> <groupId>com.itfsw</groupId> <artifactId>mybatis-generator-plugin</artifactId> <version>1.3.5</version> </dependency>
反向代理規則文件 mybatis-generator.xmlgit
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="testTables" targetRuntime="MyBatis3"> <!-- 自動爲entity生成swagger2文檔--> <plugin type="mybatis.generator.plugins.GeneratorSwagger2Doc"> <property name="apiModelAnnotationPackage" value="io.swagger.annotations.ApiModel" /> <property name="apiModelPropertyAnnotationPackage" value="io.swagger.annotations.ApiModelProperty" /> </plugin> <!-- Example 目標包修改插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin"> <property name="targetPackage" value="com.yao.dataforsea_bg.db.dao.example"/> </plugin> <!-- Lombok插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.LombokPlugin"> <!-- @Data 默認開啓,同時插件會對子類自動附加@EqualsAndHashCode(callSuper = true),@ToString(callSuper = true) --> <property name="@Data" value="true"/> <!-- @Builder 必須在 Lombok 版本 >= 1.18.2 的狀況下開啓,對存在繼承關係的類自動替換成@SuperBuilder --> <property name="@Builder" value="false"/> <!-- @NoArgsConstructor 和 @AllArgsConstructor 使用規則和Lombok一致 --> <property name="@AllArgsConstructor" value="false"/> <property name="@NoArgsConstructor" value="false"/> <!-- @Getter、@Setter、@Accessors 等使用規則參見官方文檔 --> <property name="@Accessors(chain = true)" value="false"/> <!-- 臨時解決IDEA工具對@SuperBuilder的不支持問題,開啓後(默認未開啓)插件在遇到@SuperBuilder註解時會調用ModelBuilderPlugin來生成相應的builder代碼 --> <property name="supportSuperBuilderForIdea" value="false"/> </plugin> <!-- Example Criteria 加強插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin"> <!-- 是否支持已通過時的andIf方法(推薦使用when代替),默認支持 --> <property name="enableAndIf" value="true"/> </plugin> <!-- Mapper註解插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.MapperAnnotationPlugin"> <!-- @Mapper 默認開啓 --> <property name="@Mapper" value="true"/> <!-- @Repository 默認關閉,開啓後解決IDEA工具@Autowired報錯 --> <property name="@Repository" value="true"/> </plugin> <!-- 自定義註釋生成器 --> <commentGenerator type="com.yao.dataforsea_bg.db.plugins.MySQLCommentGenerator"> <property name="author" value="wpy"/> <property name="dateFormat" value="yyyy/MM/dd HH:mm:ss"/> </commentGenerator> <!-- <commentGenerator> < 是否去除自動生成的註釋,true:是,false:否 > <property name="suppressAllComments" value="true"/> </commentGenerator> --> <!--數據庫鏈接的信息:驅動類、鏈接地址、用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://188.131.222.102:3306/infocrawler" userId="root" password="wangpengyao11"> </jdbcConnection> <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer,爲 true時把JDBC DECIMAL 和 NUMERIC 類型解析爲java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 指定javaBean生成的位置 targetPackage:生成的類要放的包,真實的包受enableSubPackages屬性控制; targetProject:目標項目,指定一個存在的目錄下,生成的內容會放到指定目錄中,若是目錄不存在,MBG不會自動建目錄 --> <javaModelGenerator targetPackage="com.yao.dataforsea_bg.db.model" targetProject="src/main/java"> <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false;若是多個數據庫改成true分目錄 --> <property name="enableSubPackages" value="false"/> <!-- 設置是否在getter方法中,對String類型字段調用trim()方法 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 指定mapper映射文件生成的位置 targetPackage、targetProject同javaModelGenerator中做用同樣--> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 指定mapper接口生成的位置 targetPackage、targetProject同javaModelGenerator中做用同樣 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yao.dataforsea_bg.db.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 指定數據庫表 domainObjectName:生成的domain類的名字,當表名和domain類的名字有差別時必定要設置,若是不設置,直接使用表名做爲domain類的名字; 能夠設置爲somepck.domainName,那麼會自動把domainName類再放到somepck包裏面; --> <table tableName="downloadfile" domainObjectName="DownloadFile"> <generatedKey column="id" sqlStatement="select replace(uuid(), '-', '')"></generatedKey> </table> </context> </generatorConfiguration>
最後在java類main函數調用
這裏須要注意 File 路徑默認以idea工程根目錄爲 初始目錄,所以一下代碼須要將mybatis-generator.xml放在項目根目錄,而非resource目錄github
package com.yao.dataforsea_bg.db; /** * @Author: wpy * @Email: wangpengyao@cnic.cn * @Date: 2020-03-31 21:06 */ import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.File; import java.util.ArrayList; import java.util.List; public class Generator { public static void main( String[] args ) throws Exception { List<String> warnings = new ArrayList<>(); File configFile = new File("./mybatis-generator.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(true); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } }
最後若是仔細看mybatis-generator能夠發現,我使用了一個自定義的commentGenerator,它的做用是使用數據庫remark做爲model類field註釋,去除原始生成註釋包含的沒必要要信息,它包括定義接口實現兩個類sql
/** * @Author: wpy * @Email: wangpengyao@cnic.cn * @Date: 2020-03-31 21:01 */ public class EmptyCommentGenerator implements CommentGenerator { @Override public void addConfigurationProperties(Properties properties) { } @Override public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { } @Override public void addFieldComment(Field field, IntrospectedTable introspectedTable) { } @Override public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { } @Override public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) { } @Override public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean b) { } @Override public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) { } @Override public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { } @Override public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { } @Override public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) { } @Override public void addJavaFileComment(CompilationUnit compilationUnit) { } @Override public void addComment(XmlElement xmlElement) { } @Override public void addRootComment(XmlElement xmlElement) { } }
/** * @Author: wpy * @Email: wangpengyao@cnic.cn * @Date: 2020-03-31 20:57 */ public class MySQLCommentGenerator extends EmptyCommentGenerator { private Properties properties; public MySQLCommentGenerator() { properties = new Properties(); } @Override public void addConfigurationProperties(Properties properties) { // 獲取自定義的 properties this.properties.putAll(properties); } @Override public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { String author = properties.getProperty("author"); String dateFormat = properties.getProperty("dateFormat", "yyyy-MM-dd"); SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat); // 獲取表註釋 String remarks = introspectedTable.getRemarks(); topLevelClass.addJavaDocLine("/**"); topLevelClass.addJavaDocLine(" * " + remarks); topLevelClass.addJavaDocLine(" *"); topLevelClass.addJavaDocLine(" * @author " + author); topLevelClass.addJavaDocLine(" * @date " + dateFormatter.format(new Date())); topLevelClass.addJavaDocLine(" */"); } @Override public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { // 獲取列註釋 String remarks = introspectedColumn.getRemarks(); field.addJavaDocLine("/**"); field.addJavaDocLine(" * " + remarks); field.addJavaDocLine(" */"); } }