mybatis3.2.2 sqlmap通配实现

gwn00 2013-08-06

每次都要往主SqlMapConfig的 <mappers></mappers>添加sqlmap的路径,感觉非常繁琐(不觉得繁琐的人除外)。于是我希望能够想spring一样通配路径实现这样的效果:

  <mappers>

        <mapper resource="cn/com/xxxx/**/sqlmap_*_yw.xml" />

</mappers>

当然这样的条件是命名规范(满足自己的命名规范就行)。比如这个会扫描所有cn/com/xxxx/**/sqlmap_*_yw.xml这种格式的sqlmap.xml

本来想通过spring的aop实现,不过没成,于是我只能修改源码了。如果有更好的方案的朋友可以告诉我,谢谢。

找到org.apache.ibatis.builder.xml.XMLConfigBuilder.class反编后发现:private void parseConfiguration(XNode root) 为SqlMapConfig.xml的解析入口。但是由于是private方法,所以我不得不通过修改源码实现功能。如果想通过通过反射的话就算了,得不偿失。

 private void parseConfiguration(XNode root) {

    try {

      propertiesElement(root.evalNode("properties")); //issue #117 read properties first

      typeAliasesElement(root.evalNode("typeAliases"));

      pluginElement(root.evalNode("plugins"));

      objectFactoryElement(root.evalNode("objectFactory"));

      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));

      settingsElement(root.evalNode("settings"));

      environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631

      databaseIdProviderElement(root.evalNode("databaseIdProvider"));

      typeHandlerElement(root.evalNode("typeHandlers"));  

      XNode xNode=parasMmappers(root.evalNode("mappers"));

      mapperElement(xNode);

    } catch (Exception e) {

      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);

    }

  }

  private XNode parasMmappers(XNode root){

 List<String> resourceList=new ArrayList<String>();

 ResourceLoader resourceLoader=new PathMatchingResourcePatternResolver();  

 Resource[]  a_resource;  

 List<XNode> xNodeList=root.getChildren();

 

 String resource;

 String filePath;  

try {

for (XNode item : xNodeList) {

resource = item.getStringAttribute("resource");

a_resource = ((ResourcePatternResolver) resourceLoader).getResources(resource);

for (Resource res:a_resource) {

res.getURI();

filePath=res.getFile().toString();

filePath=filePath.substring(filePath.indexOf("classes")+8);

if(resourceList.indexOf(filePath)==-1){

resourceList.add(filePath);

}

}

}

} catch (IOException e) {

log.error(e);

}

StringBuffer xmlBuff = new StringBuffer();

xmlBuff.append("<mappers>");

if (resourceList.size() > 0) {

for (String res : resourceList) {

xmlBuff.append("<mapper resource=\"");

xmlBuff.append(res);

xmlBuff.append("\" />");

}

}

xmlBuff.append("</mappers>");

XPathParser xPathParser = new XPathParser(xmlBuff.toString());

Node node = xPathParser.evalNode("mappers").getNode();

XNode xNode = new XNode(xPathParser,node , null);

return xNode;

  }

    

红色为修改和添加部分。

附上附件。自己编译后根据包路径, 继续放入mybatis-3.2.2.jar就OK了

相关推荐