MyBatis Generator代碼分析一

【原創(chuàng)文章,轉(zhuǎn)載請注明原文章地址,謝謝!】

注意:以下代碼都有適當修改和刪改,為了更好看清楚執(zhí)行流程

首先是簡單分析使用Shell Runner執(zhí)行MBG的最概略的執(zhí)行流程分析:

org.mybatis.generator.api.ShellRunner:運行MyBatis Generator 的Main入口類;####

核心代碼(main方法):

//解析命令行
Map<String, String> arguments = parseCommandLine(args);

//創(chuàng)建一個警告列表,整個MBG運行過程中的所有警告信息都放在這個列表中,執(zhí)行完成后統(tǒng)一System.out
List<String> warnings = new ArrayList<String>();

//得到generatorConfig.xml文件
String configfile = arguments.get(CONFIG_FILE);
File configurationFile = new File(configfile);

Set<String> fullyqualifiedTables = new HashSet<String>();//如果參數(shù)有tables,得到table名稱列表
Set<String> contexts = new HashSet<String>();//如果參數(shù)有contextids,得到context名稱列表

try {
    //創(chuàng)建配置解析器
    ConfigurationParser cp = new ConfigurationParser(warnings);
    //調(diào)用配置解析器創(chuàng)建配置對象(Configuration對象非常簡單,可以簡單理解為包含兩個列表,一個列表是List<Context> contexts,包含了解析出來的Context對象,一個是List<String> classPathEntries,包含了配置的classPathEntry的location值)
    Configuration config = cp.parseConfiguration(configurationFile);
    //創(chuàng)建一個默認的ShellCallback對象,之前說過,shellcallback接口主要用來處理文件的創(chuàng)建和合并,傳入overwrite參數(shù);默認的shellcallback是不支持文件合并的;
    DefaultShellCallback shellCallback = new DefaultShellCallback(
                arguments.containsKey(OVERWRITE));
    //創(chuàng)建一個MyBatisGenerator對象。MyBatisGenerator類是真正用來執(zhí)行生成動作的類
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);
    //創(chuàng)建一個默認的ProgressCallback對象,之前說過,在MBG執(zhí)行過程中在一定的執(zhí)行步驟結(jié)束后調(diào)用ProgressCallback對象的方法,達到執(zhí)行過程監(jiān)控的效果;
    //如果在執(zhí)行ShellRunner是傳入了-verbose參數(shù),那么創(chuàng)建一個VerboseProgressCallback(VerboseProgressCallback只是調(diào)用了System.out打印出了執(zhí)行過程而已)
    ProgressCallback progressCallback = arguments.containsKey(VERBOSE) ? new VerboseProgressCallback()
                : null;
    //執(zhí)行真正的MBG創(chuàng)建過程
    //注意,這里的contexts是通過-contextids傳入的需要的上下文id列表;
    //fullyqualifiedTables是通過-tables傳入的本次需要生成的table名稱列表;
    myBatisGenerator.generate(progressCallback, contexts, fullyqualifiedTables);
}catch(...){...}

//輸出警告信息
for (String warning : warnings) {
    writeLine(warning);
}

org.mybatis.generator.config.xml.ConfigurationParser:配置解析器,用于對generatorConfig.xml配置文件的解析;####

構(gòu)造方法:

//初始化配置解析器中的一些基本數(shù)據(jù)內(nèi)容
public ConfigurationParser(Properties properties, List<String> warnings) {
    super();
    if (properties == null) {
        //properties:存放的系統(tǒng)配置信息
        this.properties = System.getProperties();
    } else {
        this.properties = properties;
    }

    if (warnings == null) {
        //warnings:存放的解析中的警告信息
        this.warnings = new ArrayList<String>();
    } else {
        this.warnings = warnings;
    }
    //parseErrors :存放的解析中的錯誤信息
    parseErrors = new ArrayList<String>();
}

//執(zhí)行配置解析,創(chuàng)建配置對象
private Configuration parseConfiguration(InputSource inputSource)
        throws IOException, XMLParserException {
    parseErrors.clear();
    //使用DOM解析器解析XML
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    //設(shè)置實體對象處理器(對于MyBatis3來說,就是處理org/mybatis/generator/config/xml/mybatis-generator-config_1_0.dtd驗證),
    builder.setEntityResolver(new ParserEntityResolver());
    //設(shè)置解析錯誤處理器,把解析過程中的異常和警告保存到warnings和parseErrors兩個String列表中;
    ParserErrorHandler handler = new ParserErrorHandler(warnings,
                parseErrors);
    builder.setErrorHandler(handler);
    //得到配置文件對應(yīng)的DOM對象;
    Document document =  builder.parse(inputSource);

    //配置對象;
    Configuration config;
    Element rootNode = document.getDocumentElement();
    //得到XML文件的xml描述符;
    DocumentType docType = document.getDoctype();
    if (rootNode.getNodeType() == Node.ELEMENT_NODE
                && docType.getPublicId().equals(XmlConstants.IBATOR_CONFIG_PUBLIC_ID)) {
        //如果xml的PUBLIC_ID為-//Apache Software Foundation//DTD Apache iBATIS Ibator Configuration 1.0//EN,則執(zhí)行解析ibatis過程;
        config = parseIbatorConfiguration(rootNode);
    } else if (rootNode.getNodeType() == Node.ELEMENT_NODE
                && docType.getPublicId().equals(XmlConstants.MYBATIS_GENERATOR_CONFIG_PUBLIC_ID)) {
        //如果xml的PUBLIC_ID為-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN,則執(zhí)行解析mybatis過程;
        config = parseMyBatisGeneratorConfiguration(rootNode);
    }
    //返回解析出的Configuration對象
    return config;
}

//執(zhí)行MyBatis生成器的配置
private Configuration parseMyBatisGeneratorConfiguration(Element rootNode)
        throws XMLParserException {
    //創(chuàng)建一個MyBatisGeneratorConfigurationParser 
    MyBatisGeneratorConfigurationParser parser = new MyBatisGeneratorConfigurationParser(
            properties);
    //使用配置解析器執(zhí)行XML解析
    return parser.parseConfiguration(rootNode);
}

MyBatisGeneratorConfigurationParser :用于把MBG配置文件解析為MyBatis3需要樣式;####

public Configuration parseConfiguration(Element rootNode)
        throws XMLParserException {
    //創(chuàng)建一個新的配置對象
    Configuration configuration = new Configuration();
    //得到<generatorConfiguration>下的所有元素,并遍歷
    NodeList nodeList = rootNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);
        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        if ("properties".equals(childNode.getNodeName())) { //$NON-NLS-1$
            //如果是<properties>元素,執(zhí)行properties解析
            parseProperties(configuration, childNode);
        } else if ("classPathEntry".equals(childNode.getNodeName())) { //$NON-NLS-1$
            //如果是<classPathEntry>,執(zhí)行classPathEntry解析
            parseClassPathEntry(configuration, childNode);
        } else if ("context".equals(childNode.getNodeName())) { //$NON-NLS-1$
            //如果是<context>元素,執(zhí)行context解析
            parseContext(configuration, childNode);
        }
    }
    return configuration;
}

//所以重點是三個方法:parseProperties/parseClassPathEntry/parseContext

//parseProperties方法最重要的就是加載指定的properties配置到properties中,【注意】,因為在<generatorConfiguration>元素中的<properties>元素最重要的就是用來替換在配置文件中所有的${key}占位符,所以,properties元素只需要在解析過程存在,所以可以看到properties屬性是只需要在MyBatisGeneratorConfigurationParser中使用;
private void parseProperties(Configuration configuration, Node node)
        throws XMLParserException {
    //解析得到URL或者resource屬性(兩種配置的加載方式)
    Properties attributes = parseAttributes(node);
    String resource = attributes.getProperty("resource"); 
    String url = attributes.getProperty("url"); 
    //統(tǒng)一把resource/URL轉(zhuǎn)成URL;
    URL resourceUrl;
    if (stringHasValue(resource)) {
        resourceUrl = ObjectFactory.getResource(resource);
    } else {
        resourceUrl = new URL(url);
    }
    //從URL加載properties文件并載入;
    InputStream inputStream = resourceUrl.openConnection()
                .getInputStream();
    properties.load(inputStream);
    inputStream.close();
}

//上面是解析properties的方法,主要就是提供給這個方法使用:在配置文件中所有的屬性值都先使用${}占位符去測試一下,如果是占位符,就把${}中的值作為key去properties中查找,把查找到的值作為屬性真正的值返回;
private String parsePropertyTokens(String string) {
    final String OPEN = "${"; //$NON-NLS-1$
    final String CLOSE = "}"; //$NON-NLS-1$
    //中間代碼略,就是解析得到${}中的值,并去properties中查詢;
    return newString;
}

//解析classPathEntry元素,只是很簡單的把所有的classPathEntry元素的location添加到配置對象的classpathEntry列表中
private void parseClassPathEntry(Configuration configuration, Node node) {
    Properties attributes = parseAttributes(node);
    configuration.addClasspathEntry(attributes.getProperty("location")); //$NON-NLS-1$
}

//最重要的,最復(fù)雜的,解析context元素
private void parseContext(Configuration configuration, Node node) {
    //解析出context元素上的所有屬性,并把所有屬性放到一個properties中;
    Properties attributes = parseAttributes(node);
    /**
     * 得到默認的生成對象的樣式(ModeType是一個簡單的枚舉)
     * public enum ModelType {
            HIERARCHICAL("hierarchical"),FLAT("flat"),CONDITIONAL("conditional");
       } 
       ModelType的getModelType只是很簡單的根據(jù)string返回對應(yīng)的類型或者報錯
     */
    ModelType mt = defaultModelType == null ? null : ModelType
            .getModelType(defaultModelType);
    //創(chuàng)建一個Context對象
    Context context = new Context(mt);
    //先添加到配置對象的context列表中,
    configuration.addContext(context);
    //再解析<context>子元素
    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        //以下的內(nèi)容就很模式化了,只是依次把context的不同子元素解析,并添加到Context對象中;所以我們就先不看每一個具體的解析代碼,先看一下Context對象的結(jié)構(gòu);
        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(context, childNode);
        } else if ("plugin".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parsePlugin(context, childNode);
        } else if ("commentGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseCommentGenerator(context, childNode);
        } else if ("jdbcConnection".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseJdbcConnection(context, childNode);
        } else if ("javaModelGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseJavaModelGenerator(context, childNode);
        } else if ("javaTypeResolver".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseJavaTypeResolver(context, childNode);
        } else if ("sqlMapGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseSqlMapGenerator(context, childNode);
        } else if ("javaClientGenerator".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseJavaClientGenerator(context, childNode);
        } else if ("table".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseTable(context, childNode);
        }
    }
}

org.mybatis.generator.config.Context:封裝<context>元素內(nèi)容####

public class Context extends PropertyHolder {

/** context的id */
private String id;

/** jdbc連接配置,包裝成JDBCConnectionConfiguration 對象,對應(yīng)<jdbcConnection>元素 */
private JDBCConnectionConfiguration jdbcConnectionConfiguration;

/** 生成SQL MAP的xml配置,對應(yīng)<sqlMapGenerator>元素,包裝成 SqlMapGeneratorConfiguration 對象*/
private SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration;

/** 生成java類型處理器配置,對應(yīng)<javaTypeResolver>元素,包裝成 JavaTypeResolverConfiguration 對象 */
private JavaTypeResolverConfiguration javaTypeResolverConfiguration;

/** 生成java模型創(chuàng)建器配置,對應(yīng)<javaModelGenerator>元素,包裝成 JavaModelGeneratorConfiguration 對象 */
private JavaModelGeneratorConfiguration javaModelGeneratorConfiguration;

/** 生成Mapper接口配置,對應(yīng)<javaClientGenerator>元素,包裝成 JavaClientGeneratorConfiguration 對象*/
private JavaClientGeneratorConfiguration javaClientGeneratorConfiguration;

/** 解析每一個<table>元素,并包裝成一個一個的TableConfiguration對象 */
private ArrayList<TableConfiguration> tableConfigurations;

/** 生成對象樣式,對應(yīng)context元素的defaultModelType屬性(attribute) */
private ModelType defaultModelType;

/** 對應(yīng)context元素的beginningDelimiter這個property子元素(注意屬性和property的區(qū)別) */
private String beginningDelimiter = "\""; 

/**  對應(yīng)context元素的endingDelimiter 這個property子元素*/
private String endingDelimiter = "\""; 

/** 對應(yīng)<commentGenerator>元素,注解生成器的配置 */
private CommentGeneratorConfiguration commentGeneratorConfiguration;

/** 注解生成器 */
private CommentGenerator commentGenerator;

/** 這是一個包裝了所有的plugin的插件執(zhí)行對象,其中的插件就是由pluginConfigurations中的每一個PluginConfiguration生成*/
private PluginAggregator pluginAggregator;

/** 對應(yīng)每一個<plugin>元素的配置 */
private List<PluginConfiguration> pluginConfigurations;

/** 目標運行時,對應(yīng)context元素的targetRuntime屬性(attribute) */
private String targetRuntime;

/** 對應(yīng)context元素的introspectedColumnImpl屬性(attribute) */
private String introspectedColumnImpl;

/** 自動識別數(shù)據(jù)庫關(guān)鍵字,對應(yīng)context元素的autoDelimitKeywords這個property子元素 */
private Boolean autoDelimitKeywords;

/**Java代碼格式化工具,對應(yīng)context元素的javaFormatter這個property子元素  */
private JavaFormatter javaFormatter;

/** Xml代碼格式化工具,對應(yīng)context元素的xmlFormatter這個property子元素 */
private XmlFormatter xmlFormatter;
}

可以看到,其實MBG的初始化過程是非常簡單的,說白了,最重要的目的就是把generatorConfig.xml中的DOM通過MyBatisGeneratorConfigurationParser類解析成一個Configuration對象,而主要的工作就是消耗在把<context>元素解析成Configuration對象中的List<Context>,而<context>剛好對應(yīng)著Context對象,那么,實際的生成過程,就是MyBatisGenerator對象根據(jù)Configuration對象來生成了。

待續(xù)...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容