设为首页 收藏本站
查看: 1414|回复: 0

[经验分享] Mybatis 代码流程及实现原理解析(二)

[复制链接]

尚未签到

发表于 2016-11-28 06:44:21 | 显示全部楼层 |阅读模式
  XMLConfigBuilder.java中

  1.propertiesElement(root.evalNode("properties")); 此方法解析<properties>及其子节点。
  代码实现:

private void propertiesElement(XNode context) throws Exception {
if (context != null) {
Properties defaults = context.getChildrenAsProperties();//解析所有子节点property 值
String resource = context.getStringAttribute("resource");
String url = context.getStringAttribute("url");
if (resource != null && url != null) { //从外部引入property文件
throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
}
if (resource != null) {
defaults.putAll(Resources.getResourceAsProperties(resource));
} else if (url != null) {
defaults.putAll(Resources.getUrlAsProperties(url));
}
Properties vars = configuration.getVariables();
if (vars != null) {
defaults.putAll(vars);
}
parser.setVariables(defaults);  //这里要将property给parser,因为在后面的一些可以能会用到这些属性值。
configuration.setVariables(defaults);
}
}xml 节点样例:
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</properties>从代码可以看出:  1.先把解析子节点property 值, 然后再把外部引入进来的property信息添加到已有的properties中。
  2. 支持以resource 和url的方式引入外部的property,但是两者只能有其中之一。
  3,节点解析完以后,放入configuration类中。<properties>在这个类中的存在形式是:

protected Properties variables = new Properties();

2.typeAliasesElement(root.evalNode("typeAliases")); 此方法解析<typeAliases>及其子节点。
private void typeAliasesElement(XNode parent) {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String typeAliasPackage = child.getStringAttribute("name");
configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);//将整个包下的类添加的别名集合中。
} else {
String alias = child.getStringAttribute("alias");
String type = child.getStringAttribute("type");
try {
Class<?> clazz = Resources.classForName(type);
if (alias == null) {
typeAliasRegistry.registerAlias(clazz); //如果alias 不存在,则回去检查是否有Alias的annotation,有的话用annotation的值,没有则用type的简单类/              //名
} else {
typeAliasRegistry.registerAlias(alias, clazz);
}
} catch (ClassNotFoundException e) {
throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
}
}
}
}
}


xml 节点样例:
<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
<package name="domain.blog"/>
</typeAliases>


从代码可以看出:
  1. 如果有<package>子节点, 则将整个包中的类放入到别名集合中。
  2. 如果是<typeAlias>子节点, 则直接放入到别名集合中。
  3. 放入别名集合的原则是:如果alias 不存在,则回去检查是否有Alias的annotation,有的话用annotation的值,没有则把type的简单类名当做alias。 并且alias所代表的type不能有重复。 相关实现可以参考类TypeAliasRegistry.java
  
3. pluginElement,objectFactoryElement,objectWrapperFactoryElement,settingsElement,environmentsElement,databaseIdProviderElement,typeHandlerElement 就不一个一个分析, 都是去解析相关节点,然后放入Configuration.java 这个类中。
  

  4. mapperElement(root.evalNode("mappers"));此方法解析<mappers>及其子节点。
  

private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}


xml 节点样例
<mappers>
<mapper resource="com/skoyou/mapper/User.xml"/>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<package name="org.mybatis.builder"/>
</mappers>


从代码可以看出:  1. 当前支持四种方式来加载mapper内容: resource,url,class,package。
  class方式直接把class的类类型加入到configuration类的相关mapper变量中。这个变量就是MapperRegistry.java
  package方式会多一个操作就是找出该package(包含子包)下的类。
  看addmapper的实现:具体在MapperRegistry.java中。


public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
knownMappers.put(type, new MapperProxyFactory<T>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}实际上 mapper类型只能是接口,且不能重复加入。 由于package和class的方式是直接引入mapper接口,具体的sql或mapper文件是通过注解的方式加入到这个接口的。所以addMapper方法还会进行一些额外的解析。 具体在此方法的中调用的MapperAnnotationBuilder的parse()方法。
  public void parse() {
String resource = type.toString();
if (!configuration.isResourceLoaded(resource)) {
loadXmlResource(); //尝试加载同名的mapper文件,没有的话就不处理
configuration.addLoadedResource(resource);
assistant.setCurrentNamespace(type.getName());
parseCache();
parseCacheRef();
Method[] methods = type.getMethods();
for (Method method : methods) {
try {
parseStatement(method); //主要是看方法上面有没有相关注解(@select,@update等)
} catch (IncompleteElementException e) {
configuration.addIncompleteMethod(new MethodResolver(this, method));
}
}
}
parsePendingMethods();
}



  url,resource方式是从外部引入新的mapper文件, 对外部文件解析之后再将转换后的内容加入到configuration中。


看XMLMapperBuilder.parse()方法:

public void parse() {
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper"));// 具体解析mapper文件
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
parsePendingResultMaps();
parsePendingChacheRefs();
parsePendingStatements();
}


下篇会具体看看configurationElement() 这个方法, 因为mapper文件的各节点解析都在这个文件中。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-306287-1-1.html 上篇帖子: Mybatis源代码分析之parsing包【转】 下篇帖子: 搭建基于全注解的Spring+Spring MVC+MyBatis框架
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表