`
zhangwei_david
  • 浏览: 474710 次
  • 性别: 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
分享到:
评论

相关推荐

    SqlMapClient对象.pdf

    SqlMapClient对象是iBatis框架中用于操作数据库的核心接口,它提供了对数据库的基本CRUD(创建、读取、更新、删除)操作的支持,并且包含了事务管理功能。SqlMapClient的设计模式类似于Hibernate中的SessionFactory...

    iBATIS框架源码剖析源码

    这个框架的主要目的是将SQL映射到Java代码中,使得开发者能够避免直接处理JDBC的繁琐过程,从而更加专注于业务逻辑的实现。iBATIS的核心在于它的SQL Maps,这是一种XML配置文件,用于定义SQL查询和结果集映射。 在...

    SqlMapClient对象.docx

    由于`SqlMapClient`是线程安全的,因此在实际应用中,通常会将其作为单例模式来创建和使用,类似于Hibernate中的`SessionFactory`。 初始化`SqlMapClient`对象通常需要一个配置文件,这个配置文件包含了数据源、...

    ibatis2.3源码

    【标题】"ibatis2.3源码"指的是开源的SQL映射框架iBATIS的2.3版本的源代码。iBATIS是Java平台上的一种轻量级持久层框架,它将SQL语句与Java代码分离,使得开发者可以更加灵活地处理数据库操作。 【描述】中的"可以...

    ibatis实战之基础环境搭建(源码).zip

    iBatis的核心是SqlMapConfig.xml配置文件,它包含了数据源、事务管理器、SqlMapClient以及其他的全局设置。在搭建环境中,我们需要创建这个配置文件,并正确配置数据库连接信息。 1. **环境准备**: - 安装Java ...

    Ibatis框架三层架构项目源码.rar

    在Ibatis框架中,DAL通常会包含SQLMapClient配置文件,定义了SQL语句和Java对象之间的映射关系。此外,还会包含DAO(Data Access Object)接口和实现类,接口定义了业务逻辑所需的操作,实现类则利用Ibatis的...

    ibatis源码 例子

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

    ibatis2.3.4.726增删改查源码实例

    1. **SqlMapConfig.xml**:这是Ibatis全局配置文件,包含数据源配置、事务管理器配置、SqlMapClient配置等。在这个实例中,你可能在`.settings`或`src`目录下找到这个文件,它是整个Ibatis框架的起点。 2. **Mapper...

    ibatis-sqlmap-2.3.4.726-sources.jar.zip_birth84v_cutting1v2_ibat

    它通过SqlMapConfigParser解析SqlMapConfig.xml文件,创建SqlMap实例。SqlMap则包含了对数据库操作的具体配置,包括数据源、事务管理等。对于SQL语句的执行,SqlMapClient使用Executor接口,该接口定义了不同类型的...

    ibatis2.3-src

    - **SqlMap接口与SqlMapClient**:SqlMap接口定义了操作数据库的基本方法,SqlMapClient是其实现,负责处理SQL映射文件并执行SQL。 - **Statement**:包括了PreparedStatement和SimpleStatement,用于执行SQL语句...

    IBatisNet-执行存储过程-mysql 请点击分页按钮

    你需要使用`SqlMapClient`对象来执行存储过程,如下所示: ```csharp public class UserService { private ISqlMapper sqlMap; public UserService(ISqlMapper sqlMap) { this.sqlMap = sqlMap; } public ...

    SS+I 实例源码下载

    4. **ibatis-config.xml**:iBATIS的配置文件,包含了数据源、SqlMapClient等配置。 5. ***.java** 文件:包括Action类(处理HTTP请求),ActionForm类(封装请求参数),Service接口和实现类(业务逻辑),DAO接口...

    ibatis+jndi+mysql

    1. **创建存储过程** - 在数据库中编写存储过程,定义输入和输出参数。 2. **调用存储过程** - 在 Emp.xml 文件中使用 `&lt;procedure&gt;` 标签调用存储过程,并设置相应的参数。 3. **实现类调用** - 在 Java 代码中,...

    iBATIS 框架简介

    1. 创建SqlMapClient实例,配置数据源和SqlMap配置文件。 2. 通过SqlMapClient获取SqlMapSession实例。 3. 在SqlMapSession上下文中执行SQL语句,传入参数。 4. 获取执行结果,通过ResultMap映射为Java对象。 5. ...

    iBATIS-DAO-2.3.4.726.rar_com.ibatis.dao_iBATIS dao 2_iBatis DAO_

    在源码分析过程中,通过添加注释,我们可以清晰地了解每个类和方法的功能,以及它们之间的调用关系。例如,注释可以解释`SqlMapExecutor`如何根据`SqlMapClient`提供的配置信息来执行SQL,以及`SqlMapSession`如何...

    IBatisNet源代码

    **IBatisNet源代码分析** IBatisNet是一个流行的开源数据访问框架,它为.NET开发者提供了简单而强大的数据映射...同时,熟悉IBatisNet源码也有助于开发者更好地与其他基于IBatisNet的项目协同工作,提升整体开发效率。

    iBatis2.X入门附带完整项目

    XML配置文件用于定义SQL语句、存储过程和结果映射,SqlMapClient是数据访问的入口,SqlMapConfig.xml是全局配置文件,而SqlMap接口则对应数据库操作的DAO层。 首先,让我们深入理解XML配置文件。在这里,你可以看到...

    ibatis的技术总结

    这是iBatis的核心部分之一,用于定义如何将SQL语句和Java对象进行映射。 6. **编写代码:** 在Java源文件中编写业务逻辑代码,利用iBatis提供的API进行数据库操作。这包括获取SqlMapClient实例、调用查询、更新等...

    ibatis批量处理

    iBatis(现已更名为MyBatis)是一款优秀的持久层框架,它支持定制化SQL、存储过程及高级映射。iBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。iBatis可以非常简单地将接口和Java的POJOs(Plain Old ...

    ibatis 使用简单配置

    下面是创建`SqlMapClient`实例的一个示例类`SqlMapUtil`,该类通过静态方法`getSqlMapClient()`返回`SqlMapClient`实例。 ```java import java.io.IOException; import com.ibatis.common.resources.Resources...

Global site tag (gtag.js) - Google Analytics