使用Java程式碼配置MyBatis Generator

歲月已走遠發表於2020-06-14

  使用MyBatis Generator生成器時,有時候沒辦法使用xml型的配置檔案,比如將Maven專案設定成pom打包方式(<packaging>pom</packaging>)!由於Maven的工作機制對於打包方式為pom的專案是不會輸出jar包或war和resources內容,所以放在resources目錄下或放在原始碼目錄下的xml檔案就沒法讀取了,就算你在pom.xml檔案中明確有如下配置也沒有用的:

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.yml</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.yml</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

  這個時候就會用到純Java程式碼的MyBatis Generator配置,直接貼配置程式碼:

import org.mybatis.generator.config.*;

/**
 * 基礎Java程式碼的MBG配置
 * Maven打包方式為POM的專案或模組(<packaging>pom</packaging>),resources目錄的內容不會輸出到類路徑下,所以可以選擇直接使用Java程式碼配置!
 *
 * @author 707669522@qq.com
 * @since 2020-06-13
 */
public class GeneratorConfig {
    public static Configuration getGeneratorConfig() {
        Context context = new Context(ModelType.CONDITIONAL);
        context.setId("simple");
        context.setTargetRuntime("MyBatis3Simple");

        /*新增屬性*/
        context.addProperty("javaFileEncoding", "UTF-8");

        /*外掛配置,這個是我自己的外掛,沒有自定義外掛的同學可以不配這一節,刪除即可*/
        PluginConfiguration pluginConfig = new PluginConfiguration();
        pluginConfig.setConfigurationType("com.xgclassroom.generator.GeneratorPlugin"); 
        context.addPluginConfiguration(pluginConfig);

        /*註釋生成器配置*/
        CommentGeneratorConfiguration commentGeneratorConfig = new CommentGeneratorConfiguration();
        commentGeneratorConfig.addProperty("suppressAllComments", "true");
        context.setCommentGeneratorConfiguration(commentGeneratorConfig);

        /*JDBC連線資訊配置*/
        JDBCConnectionConfiguration jdbcConnectionConfig = new JDBCConnectionConfiguration();
        jdbcConnectionConfig.setDriverClass("com.mysql.cj.jdbc.Driver");
        //注意程式碼配置中JDBC連線字串中的引數分隔符不需要再像xml配置檔案中那樣使用轉義符
        jdbcConnectionConfig.setConnectionURL("jdbc:mysql://localhost:3306/permission_center?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false");
        jdbcConnectionConfig.setUserId("xurm");
        jdbcConnectionConfig.setPassword("1qaz@WSX");
        jdbcConnectionConfig.addProperty("nullCatalogMeansCurrent", "true");//MySQL無法識別table標籤中schema類的配置,所以在URL上指明目標資料庫,並追加nullCatalogMeansCurrent屬性為true
        jdbcConnectionConfig.addProperty("remarksReporting", "true");//針對oracle資料庫無法讀取表和欄位備註
        jdbcConnectionConfig.addProperty("useInformationSchema", "true");//針對mysql資料庫無法讀取表和欄位備註
        context.setJdbcConnectionConfiguration(jdbcConnectionConfig);

        /*Model生成器配置*/
        JavaModelGeneratorConfiguration javaModelGeneratorConfig = new JavaModelGeneratorConfiguration();
        javaModelGeneratorConfig.setTargetProject("permission/src/main/java");//目標專案(原始碼主路徑)
        javaModelGeneratorConfig.setTargetPackage("com.xgclassroom.model");//目標包(Model類檔案存放包)
        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfig);

        /*SqlMapper生成器配置(*Mapper.xml類檔案),要javaClient生成器型別配合*/
        SqlMapGeneratorConfiguration sqlMapGeneratorConfig = new SqlMapGeneratorConfiguration();
        sqlMapGeneratorConfig.setTargetProject("permission/src/main/java");//目標專案(原始碼主路徑)
        sqlMapGeneratorConfig.setTargetPackage("com.xgclassroom.mapper");//目標包(*Mapper.xml類檔案存放包)
        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfig);

        /*JavaClient生成器配置(*Mapper.java類檔案)*/
        JavaClientGeneratorConfiguration javaClientGeneratorConfig = new JavaClientGeneratorConfiguration();
        javaClientGeneratorConfig.setConfigurationType("XMLMAPPER");//JavaClient生成器型別(主要有ANNOTATEDMAPPER、MIXEDMAPPER、XMLMAPPER,要Context的TargetRuntime配合)
        javaClientGeneratorConfig.setTargetProject("permission/src/main/java");//目標專案(原始碼主路徑)
        javaClientGeneratorConfig.setTargetPackage("com.xgclassroom.mapper");//目標包(*Mapper.java類檔案存放包)
        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfig);

        /*表生成配置*/
        TableConfiguration tableConfig = new TableConfiguration(context);
        tableConfig.setTableName("%");
        GeneratedKey generatedKey = new GeneratedKey("id", "JDBC", true, null);//設定主鍵列和生成方式
        tableConfig.setGeneratedKey(generatedKey);
        context.addTableConfiguration(tableConfig);

        Configuration config = new Configuration();
        config.addContext(context);

        return config;
    }
}

 

  然後就是把MyBatis Generator呼叫過程中原本讀取xml配置檔案的地方換掉就可以了:

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * MyBatisGenerator程式碼生成器Java呼叫程式
 *
 * @author 707669522@qq.com
 * @since 2020-06-13
 */
public class GeneratorRunner {
    public static void main(String[] args) {
        try {
            List<String> warnings = new ArrayList<String>();
            Configuration config;
            //使用xml配置檔案的方式
            /*File configFile = new File(GeneratorRunner.class.getClassLoader().getResource("generatorConfig.xml").getPath());
            ConfigurationParser cp = new ConfigurationParser(warnings);
            config = cp.parseConfiguration(configFile);*/
            //使用純Java程式碼配置的方式
            config = GeneratorConfig.getGeneratorConfig();
            DefaultShellCallback callback = new DefaultShellCallback(true);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

 

  Talk is cheap, show me the code! Bye.

相關文章