`
zhangwei_david
  • 浏览: 470116 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

SqlMapClient 创建过程之SqlMapConfigParser源码走读

 
阅读更多

 

public class SqlMapConfigParser {
	//初始化 NodeletParser
  protected final NodeletParser parser = new NodeletParser();
  //初始化XmlParserState
  private XmlParserState state = new XmlParserState();

  private boolean usingStreams = false;

  public SqlMapConfigParser() {
    parser.setValidation(true);
    parser.setEntityResolver(new SqlMapClasspathEntityResolver());
	//解析sqlMapConfig
    addSqlMapConfigNodelets();
	//解析全局属性
    addGlobalPropNodelets();
	//解析环境参数
    addSettingsNodelets();
	//解析别名配置
    addTypeAliasNodelets();
	//解析类型处理器
    addTypeHandlerNodelets();
	//解析事务
    addTransactionManagerNodelets();
	//解析sqlMap
    addSqlMapNodelets();
	//解析结果对象工厂配置
    addResultObjectFactoryNodelets();

  }

  public SqlMapClient parse(Reader reader, Properties props) {
    if (props != null) state.setGlobalProps(props);
    return parse(reader);
  }

  public SqlMapClient parse(Reader reader) {
    try {
      usingStreams = false;

      parser.parse(reader);
      return state.getConfig().getClient();
    } catch (Exception e) {
      throw new RuntimeException("Error occurred.  Cause: " + e, e);
    }
  }

  public SqlMapClient parse(InputStream inputStream, Properties props) {
    if (props != null) state.setGlobalProps(props);
    return parse(inputStream);
  }

  public SqlMapClient parse(InputStream inputStream) {
    try {
      usingStreams = true;

      parser.parse(inputStream);
      return state.getConfig().getClient();
    } catch (Exception e) {
      throw new RuntimeException("Error occurred.  Cause: " + e, e);
    }
  }

  private void addSqlMapConfigNodelets() {
    parser.addNodelet("/sqlMapConfig/end()", new Nodelet() {
      public void process(Node node) throws Exception {
        state.getConfig().finalizeSqlMapConfig();
      }
    });
  }
//解析sqlmap的属性配置
  private void addGlobalPropNodelets() {
    parser.addNodelet("/sqlMapConfig/properties", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        String resource = attributes.getProperty("resource");
        String url = attributes.getProperty("url");
        state.setGlobalProperties(resource, url);
      }
    });
  }
 //解析sqlMapConfig setting节点数据
  private void addSettingsNodelets() {
    parser.addNodelet("/sqlMapConfig/settings", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
		//获取SqlMapConfiguration对象
        SqlMapConfiguration config = state.getConfig();
		//获取classInfoCacheEnabled属性值
        String classInfoCacheEnabledAttr = attributes.getProperty("classInfoCacheEnabled");
		//如果没有配置该属性,或将该属性设置为true则将sqlMapConfiguration的值设置为true
        boolean classInfoCacheEnabled = (classInfoCacheEnabledAttr == null || "true".equals(classInfoCacheEnabledAttr));
        config.setClassInfoCacheEnabled(classInfoCacheEnabled);
		// 获取lazyLoadingEnabled属性值,是否启用懒加载
        String lazyLoadingEnabledAttr = attributes.getProperty("lazyLoadingEnabled");
		//默认是开启lazyLoadingEnabled
        boolean lazyLoadingEnabled = (lazyLoadingEnabledAttr == null || "true".equals(lazyLoadingEnabledAttr));
        config.setLazyLoadingEnabled(lazyLoadingEnabled);
		//获取statementCachingEnabled属性值,是否开启statement的缓存
        String statementCachingEnabledAttr = attributes.getProperty("statementCachingEnabled");
		//默认是开启的
        boolean statementCachingEnabled = (statementCachingEnabledAttr == null || "true".equals(statementCachingEnabledAttr));
        config.setStatementCachingEnabled(statementCachingEnabled);
		//获取cachedModelsEnabled的属性值,默认是true,该值是表示是否开启SqlMapClient上的缓存机制
        String cacheModelsEnabledAttr = attributes.getProperty("cacheModelsEnabled");
        boolean cacheModelsEnabled = (cacheModelsEnabledAttr == null || "true".equals(cacheModelsEnabledAttr));
        config.setCacheModelsEnabled(cacheModelsEnabled);
		// 获取enhancementEnabled的属性值,默认是true,该值表示是否针对POJO开启字节码增强机制,减少reflet的性能开销
        String enhancementEnabledAttr = attributes.getProperty("enhancementEnabled");
        boolean enhancementEnabled = (enhancementEnabledAttr == null || "true".equals(enhancementEnabledAttr));
        config.setEnhancementEnabled(enhancementEnabled);
		//获取useColumnLabel的属性值,默认是true
        String useColumnLabelAttr = attributes.getProperty("useColumnLabel");
        boolean useColumnLabel = (useColumnLabelAttr == null || "true".equals(useColumnLabelAttr));
        config.setUseColumnLabel(useColumnLabel);
		//获取forceMultipleResultSetSupport的属性值,默认值是false
        String forceMultipleResultSetSupportAttr = attributes.getProperty("forceMultipleResultSetSupport");
        boolean forceMultipleResultSetSupport = "true".equals(forceMultipleResultSetSupportAttr);
        config.setForceMultipleResultSetSupport(forceMultipleResultSetSupport);
		//获取defaultSatementTimeout的属性值,默认值是null;JDBC连接的超时时间,默认是无时间限制
        String defaultTimeoutAttr = attributes.getProperty("defaultStatementTimeout");
        Integer defaultTimeout = defaultTimeoutAttr == null ? null : Integer.valueOf(defaultTimeoutAttr);
        config.setDefaultStatementTimeout(defaultTimeout);
		//获取useStatementNamespaces的属性值,默认值是false:是否使用命名空间
        String useStatementNamespacesAttr = attributes.getProperty("useStatementNamespaces");
        boolean useStatementNamespaces = "true".equals(useStatementNamespacesAttr);
        state.setUseStatementNamespaces(useStatementNamespaces);
      }
    });
  }

  private void addTypeAliasNodelets() {
    parser.addNodelet("/sqlMapConfig/typeAlias", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties prop = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        String alias = prop.getProperty("alias");
        String type = prop.getProperty("type");
        state.getConfig().getTypeHandlerFactory().putTypeAlias(alias, type);
      }
    });
  }
// 解析SqlMapConfig中typeHandler节点配置
  private void addTypeHandlerNodelets() {
    parser.addNodelet("/sqlMapConfig/typeHandler", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties prop = NodeletUtils.parseAttributes(node, state.getGlobalProps());
		//获取jdbcType,javaType,callback的属性值
        String jdbcType = prop.getProperty("jdbcType");
        String javaType = prop.getProperty("javaType");
        String callback = prop.getProperty("callback");
		//根据javaType,callback作为别名去TypeHandlerFactory获取映射值,如果不是别名则返回原始值
        javaType = state.getConfig().getTypeHandlerFactory().resolveAlias(javaType);
        callback = state.getConfig().getTypeHandlerFactory().resolveAlias(callback);
		//在SqlMapConfiguration实例中设置TypeHandler
        state.getConfig().newTypeHandler(Resources.classForName(javaType), jdbcType, Resources.instantiate(callback));
      }
    });
  }
// 解析SqlMapConfig中transactionManager节点下的属性配置
  private void addTransactionManagerNodelets() {
    parser.addNodelet("/sqlMapConfig/transactionManager/property", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        String name = attributes.getProperty("name");
        String value = NodeletUtils.parsePropertyTokens(attributes.getProperty("value"), state.getGlobalProps());
        state.getTxProps().setProperty(name, value);
      }
    });
    parser.addNodelet("/sqlMapConfig/transactionManager/end()", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        String type = attributes.getProperty("type");
        boolean commitRequired = "true".equals(attributes.getProperty("commitRequired"));

        state.getConfig().getErrorContext().setActivity("configuring the transaction manager");
        type = state.getConfig().getTypeHandlerFactory().resolveAlias(type);
        TransactionManager txManager;
        try {
          state.getConfig().getErrorContext().setMoreInfo("Check the transaction manager type or class.");
          TransactionConfig config = (TransactionConfig) Resources.instantiate(type);
          config.setDataSource(state.getDataSource());
          state.getConfig().getErrorContext().setMoreInfo("Check the transactio nmanager properties or configuration.");
          config.setProperties(state.getTxProps());
          config.setForceCommit(commitRequired);
          config.setDataSource(state.getDataSource());
          state.getConfig().getErrorContext().setMoreInfo(null);
          txManager = new TransactionManager(config);
        } catch (Exception e) {
          if (e instanceof SqlMapException) {
            throw (SqlMapException) e;
          } else {
            throw new SqlMapException("Error initializing TransactionManager.  Could not instantiate TransactionConfig.  Cause: " + e, e);
          }
        }
        state.getConfig().setTransactionManager(txManager);
      }
    });
	//解析dataSource属性
    parser.addNodelet("/sqlMapConfig/transactionManager/dataSource/property", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        String name = attributes.getProperty("name");
        String value = NodeletUtils.parsePropertyTokens(attributes.getProperty("value"), state.getGlobalProps());
        state.getDsProps().setProperty(name, value);
      }
    });
    parser.addNodelet("/sqlMapConfig/transactionManager/dataSource/end()", new Nodelet() {
      public void process(Node node) throws Exception {
        state.getConfig().getErrorContext().setActivity("configuring the data source");

        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());

        String type = attributes.getProperty("type");
        Properties props = state.getDsProps();

        type = state.getConfig().getTypeHandlerFactory().resolveAlias(type);
        try {
          state.getConfig().getErrorContext().setMoreInfo("Check the data source type or class.");
          DataSourceFactory dsFactory = (DataSourceFactory) Resources.instantiate(type);
          state.getConfig().getErrorContext().setMoreInfo("Check the data source properties or configuration.");
          dsFactory.initialize(props);
          state.setDataSource(dsFactory.getDataSource());
          state.getConfig().getErrorContext().setMoreInfo(null);
        } catch (Exception e) {
          if (e instanceof SqlMapException) {
            throw (SqlMapException) e;
          } else {
            throw new SqlMapException("Error initializing DataSource.  Could not instantiate DataSourceFactory.  Cause: " + e, e);
          }
        }
      }
    });
  }


  protected void addSqlMapNodelets() {
  //解析sqlMap
    parser.addNodelet("/sqlMapConfig/sqlMap", new Nodelet() {
      public void process(Node node) throws Exception {
        state.getConfig().getErrorContext().setActivity("loading the SQL Map resource");

        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());

        String resource = attributes.getProperty("resource");
        String url = attributes.getProperty("url");

        if (usingStreams) {
          InputStream inputStream = null;
          if (resource != null) {
            state.getConfig().getErrorContext().setResource(resource);
            inputStream = Resources.getResourceAsStream(resource);
          } else if (url != null) {
            state.getConfig().getErrorContext().setResource(url);
            inputStream = Resources.getUrlAsStream(url);
          } else {
            throw new SqlMapException("The <sqlMap> element requires either a resource or a url attribute.");
          }
		//使用SQLMapParser解析sqlMap
          new SqlMapParser(state).parse(inputStream);
        } else {
          Reader reader = null;
          if (resource != null) {
            state.getConfig().getErrorContext().setResource(resource);
            reader = Resources.getResourceAsReader(resource);
          } else if (url != null) {
            state.getConfig().getErrorContext().setResource(url);
            reader = Resources.getUrlAsReader(url);
          } else {
            throw new SqlMapException("The <sqlMap> element requires either a resource or a url attribute.");
          }

          new SqlMapParser(state).parse(reader);
        }
      }
    });
  }
//解析resultObjectFactory
  private void addResultObjectFactoryNodelets() {
    parser.addNodelet("/sqlMapConfig/resultObjectFactory", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        String type = attributes.getProperty("type");

        state.getConfig().getErrorContext().setActivity("configuring the Result Object Factory");
        ResultObjectFactory rof;
        try {
          rof = (ResultObjectFactory) Resources.instantiate(type);
          state.getConfig().setResultObjectFactory(rof);
        } catch (Exception e) {
          throw new SqlMapException("Error instantiating resultObjectFactory: " + type, e);
        }

      }
    });
    parser.addNodelet("/sqlMapConfig/resultObjectFactory/property", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        String name = attributes.getProperty("name");
        String value = NodeletUtils.parsePropertyTokens(attributes.getProperty("value"), state.getGlobalProps());
        state.getConfig().getDelegate().getResultObjectFactory().setProperty(name, value);
      }
    });
  }

}

 

0
0
分享到:
评论

相关推荐

    ibatis源码 例子

    ibatis 源码 例子 包含 源码,jar都有 部分代码 package com.icss.dao; import java.io.IOException; import java.io.Reader; import java.sql.SQLException; import java.util.List; import ...

    SqlMapClient对象.pdf

    。。。

    SqlMapClient对象.docx

    。。。

    iBatis-设置缓存模式-Java源码(下载)

    SqlMapClient sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); return sqlMapper; } public void executeSQLCommand(String sql) throws Exception { st.executeUpdate(sql...

    传智播客ibatis视频教程源代码

    private static SqlMapClient sqlMapClient = null; static { try { Reader reader = com.ibatis.common.resources.Resources.getResourceAsReader("com/itcast/SqlMapConfig.xml"); sqlMapClient = ...

    Spring高版本对ibatis的支持

    &lt;bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"&gt; &lt;value&gt;classpath:SqlMapConfig.xml &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; ...

    ibatis与Spring整合例子

    SqlMapClient对象是iBATIS中的主要对象,我们可以通过配置让spring来管理SqlMapClient对象的创建。 与hibernate类似,Spring 提供了SqlMapClientDaoSupport对象,我们的DAO可以继承这个类,通过它所提供的...

    IBATIS实用记录

    3.3 SQLMAPCLIENT基本操作示例 6 3.3.1 数据写入操作(insert, update, delete) 6 3.3.2 数据查询 (select) 7 3.3.3 在指定对象中存放查询结果(select) 7 3.3.4 执行批量查询 (select) 7 3.3.5 关于AutoCommit 7 ...

    SSI框架整合实例

    部分配置代码,所有代码都有,很全 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;value&gt;classpath:jdbc... &lt;property name="sqlMapClient" ref="sqlMapClient"&gt; &lt;/bean&gt;

    ibatis例子=》包含了常用方法介绍

    包含SqlMapClient里全部方法的介绍,附带了数据库,绝对的原创,本资源绝对的免费 /* * 带参数的queryForMap用法 */ @SuppressWarnings("unchecked") public Map queryForMap(String sql_name, Object ...

    Spring.3.x企业应用开发实战(完整版).part2

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架...

    Spring3.x企业应用开发实战(完整版) part1

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架...

    ibatis API参考文档

    ibatis API参考文档,用于查询ibatis框架中所用到的类和方法,包括主要对象sqlMapClient等

    ibatis入门--对数据库的操作

    全面介绍了关于ibatis操作数据库的各种类型,在程序中编辑SqlMapClient对象的成员函数的参数,从而对数据库进行更新

    iBatis SQL Maps开发指南.pdf

    存储过程 parameterClass parameterMap Inline Parameter简介 resultClass resultMap cacheModel xmlResultName Parameter Map 和 Inline Parameter 元素 Inline Parameter Map 基本类型输入参数 Map类型输入参数 ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    创建SqlMapClient 12.5.3.2. 使用 SqlMapClientTemplate 和 SqlMapClientDaoSupport 12.5.3.3. 基于原生的iBATIS API的DAO实现 12.6. JPA 12.6.1. 在Spring环境中建立JPA 12.6.1.1. LocalEntityManagerFactoryBean...

    Spring中文帮助文档

    12.5.1. 创建SqlMapClient 12.5.2. 使用 SqlMapClientTemplate 和 SqlMapClientDaoSupport 12.5.3. 基于原生的iBATIS API的DAO实现 12.6. JPA 12.6.1. 在Spring环境中建立JPA 12.6.2. JpaTemplate 和 ...

    Spring API

    12.5.1. 创建SqlMapClient 12.5.2. 使用 SqlMapClientTemplate 和 SqlMapClientDaoSupport 12.5.3. 基于原生的iBATIS API的DAO实现 12.6. JPA 12.6.1. 在Spring环境中建立JPA 12.6.2. JpaTemplate 和 ...

    ibatis框架所需的jar包

    对于初学ibatis者来说,百度上都只提到用ibatis-2.3.0.677.jar,然后在读取配置文件的时候引用不到Resources和SqlMapClient,那么就是少了一个ibatis-sqlmap-2.3.4.726.jar,我把这两个jar同时上传了,希望可以帮助...

    springmvc-ibatis

    &lt;property name="sqlMapClient" ref="sqlMapClient"/&gt; &lt;!-- 配置 transactionManager事物管理--&gt; &lt;!-- Spring AOP config配置切点 --&gt; (* com.org.service.*.*(..))" id="bussinessService" /...

Global site tag (gtag.js) - Google Analytics