mark mybatis annotation driven

炸雞店老闆發表於2017-12-28

mybatis annotaion方式並不像spring,需要指定annotation-driven來啟用annotaion特性。
mybatis預設支援annotation,參考MapperRegistry#addMapper

/**
 * MapperRegistry Configuration實現annotaion mapper註冊的幫助類
 **/
public <T> void addMapper(Class<T> type) {
    if (type.isInterface()) {
        try {
          MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
          parser.parse();
        } finally {
            //...
        }
    }
}

接下來就是對Method物件的parse,解析出完整的mapped-statement 配置

public void parse() {
    // Class級別解析
    parseCache();
    parseCacheRef();
    Method[] methods = type.getMethods();
    // Method級別解析
    for (Method method : methods) {
        try {
            // 根據Annotation解析完整的MappedStatement資訊
            parseStatement(method);
        } catch (IncompleteElementException e) {
            // 加入待處理佇列
            configuration.addIncompleteMethod(new MethodResolver(this, method));
        }
    }
    // 再次嘗試解析 IncompleteMethod
    parsePendingMethods();
}

最後,將解析完的mapped-statement 歸入configuration

MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType);
// ......
MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);

附:mybatis Mapper XML 解析順序

  1. 迴圈指定的mapperLocations,建立對應XMLMapperBuilder
  2. 解析mapper node,addMappedStatement
  3. guess xml namespace(Class),引入Annotation處理流程
  4. 建立MapperAnnotationBuilder
  5. 解析 Class.method annotation,addMappedStatement
  6. ……

相關文章