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.");
         }
       }
     }
   }
 }
 /**
  * 使用DataSource初始化SqlSessionFactory
  *
  * @param ds
  */
 public static void initialize(DataSource ds) {
   TransactionFactory transactionFactory = new MybatisTransactionFactory();
   Environment environment = new Environment("snaker", transactionFactory, ds);
   Configuration configuration = new Configuration(environment);
   configuration.getTypeAliasRegistry().registerAliases(SCAN_PACKAGE, Object.class);
   if (log.isInfoEnabled()) {
     Map<String, Class<?>> typeAliases = configuration.getTypeAliasRegistry().getTypeAliases();
     for (Entry<String, Class<?>> entry : typeAliases.entrySet()) {
       log.info(
           "Scanned class:[name=" + entry.getKey() + ",class=" + entry.getValue().getName() + "]");
     }
   }
   try {
     for (String resource : resources) {
       InputStream in = Resources.getResourceAsStream(resource);
       XMLMapperBuilder xmlMapperBuilder =
           new XMLMapperBuilder(in, configuration, resource, configuration.getSqlFragments());
       xmlMapperBuilder.parse();
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     ErrorContext.instance().reset();
   }
   sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
 }
 private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
   super(new Configuration());
   ErrorContext.instance().resource("SQL Mapper Configuration");
   this.configuration.setVariables(props);
   this.parsed = false;
   this.environment = environment;
   this.parser = parser;
 }
  /** {@inheritDoc} */
  public Configuration get() {
    final Configuration configuration = new Configuration(environment);
    configuration.setLazyLoadingEnabled(lazyLoadingEnabled);
    configuration.setAggressiveLazyLoading(aggressiveLazyLoading);
    configuration.setMultipleResultSetsEnabled(multipleResultSetsEnabled);
    configuration.setUseGeneratedKeys(useGeneratedKeys);
    configuration.setUseColumnLabel(useColumnLabel);
    configuration.setCacheEnabled(cacheEnabled);
    configuration.setDefaultExecutorType(defaultExecutorType);
    configuration.setAutoMappingBehavior(autoMappingBehavior);
    configuration.setObjectFactory(objectFactory);
    configuration.setObjectWrapperFactory(objectWrapperFactory);
    configuration.setDefaultScriptingLanguage(defaultScriptingLanguageType);
    configuration.setMapUnderscoreToCamelCase(mapUnderscoreToCamelCase);
    configuration.setCallSettersOnNulls(callSettersOnNulls);
    configuration.setDefaultStatementTimeout(defaultStatementTimeout);

    try {
      if (databaseIdProvider != null) {
        configuration.setDatabaseId(databaseIdProvider.getDatabaseId(dataSource));
      }

      for (Map.Entry<String, Class<?>> alias : typeAliases.entrySet()) {
        configuration.getTypeAliasRegistry().registerAlias(alias.getKey(), alias.getValue());
      }

      for (Map.Entry<Class<?>, TypeHandler<?>> typeHandler : typeHandlers.entrySet()) {
        registerTypeHandler(configuration, typeHandler.getKey(), typeHandler.getValue());
      }

      for (TypeHandler<?> typeHandler : mappingTypeHandlers) {
        configuration.getTypeHandlerRegistry().register(typeHandler);
      }

      for (Class<?> mapperClass : mapperClasses) {
        if (!configuration.hasMapper(mapperClass)) {
          configuration.addMapper(mapperClass);
        }
      }

      for (Interceptor interceptor : plugins) {
        configuration.addInterceptor(interceptor);
      }

      if (failFast) {
        configuration.getMappedStatementNames();
      }
    } catch (Throwable cause) {
      throw new ProvisionException(
          "An error occurred while building the org.apache.ibatis.session.Configuration", cause);
    } finally {
      ErrorContext.instance().reset();
    }

    return configuration;
  }
Beispiel #5
0
 /**
  * 对SQL参数(?)设值, 参考org.apache.ibatis.executor.parameter.DefaultParameterHandler。
  *
  * @param ps 表示预编译的 SQL 语句的对象。
  * @param mappedStatement MappedStatement
  * @param boundSql SQL
  * @param parameterObject 参数对象
  * @throws java.sql.SQLException 数据库异常
  */
 @SuppressWarnings("unchecked")
 public static void setParameters(
     PreparedStatement ps,
     MappedStatement mappedStatement,
     BoundSql boundSql,
     Object parameterObject)
     throws SQLException {
   ErrorContext.instance()
       .activity("setting parameters")
       .object(mappedStatement.getParameterMap().getId());
   List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
   if (parameterMappings != null) {
     Configuration configuration = mappedStatement.getConfiguration();
     TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
     MetaObject metaObject =
         parameterObject == null ? null : configuration.newMetaObject(parameterObject);
     for (int i = 0; i < parameterMappings.size(); i++) {
       ParameterMapping parameterMapping = parameterMappings.get(i);
       if (parameterMapping.getMode() != ParameterMode.OUT) {
         Object value;
         String propertyName = parameterMapping.getProperty();
         PropertyTokenizer prop = new PropertyTokenizer(propertyName);
         if (parameterObject == null) {
           value = null;
         } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
           value = parameterObject;
         } else if (boundSql.hasAdditionalParameter(propertyName)) {
           value = boundSql.getAdditionalParameter(propertyName);
         } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)
             && boundSql.hasAdditionalParameter(prop.getName())) {
           value = boundSql.getAdditionalParameter(prop.getName());
           if (value != null) {
             value =
                 configuration
                     .newMetaObject(value)
                     .getValue(propertyName.substring(prop.getName().length()));
           }
         } else {
           value = metaObject == null ? null : metaObject.getValue(propertyName);
         }
         @SuppressWarnings("rawtypes")
         TypeHandler typeHandler = parameterMapping.getTypeHandler();
         if (typeHandler == null) {
           throw new ExecutorException(
               "There was no TypeHandler found for parameter "
                   + propertyName
                   + " of statement "
                   + mappedStatement.getId());
         }
         typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
       }
     }
   }
 }
  /**
   * TODO 刷新
   *
   * @param inputStream
   * @param resource
   * @param configuration
   * @throws NestedIOException
   */
  public static void refresh(
      java.io.InputStream inputStream, String resource, Configuration configuration)
      throws NestedIOException {

    try {
      XMLMapperBuilder xmlMapperBuilder =
          new XMLMapperBuilder(
              inputStream, configuration, resource, configuration.getSqlFragments());
      xmlMapperBuilder.parse1();
    } catch (Exception e) {
      throw new NestedIOException("Failed to parse mapping resource: '" + resource + "'", e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
  private SqlSession openSessionFromDataSource(
      ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      DataSource ds = ShardMapperProxy.getCurrentDs();
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory =
          getTransactionFactoryFromEnvironment(environment);

      tx = transactionFactory.newTransaction(ds, level, autoCommit);

      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
 private ResultMap resultMapElement(
     XNode resultMapNode, List<ResultMapping> additionalResultMappings) throws Exception {
   ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
   String id = resultMapNode.getStringAttribute("id", resultMapNode.getValueBasedIdentifier());
   String type =
       resultMapNode.getStringAttribute(
           "type",
           resultMapNode.getStringAttribute(
               "ofType",
               resultMapNode.getStringAttribute(
                   "resultType", resultMapNode.getStringAttribute("javaType"))));
   String extend = resultMapNode.getStringAttribute("extends");
   Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
   Class<?> typeClass = resolveClass(type);
   Discriminator discriminator = null;
   List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
   resultMappings.addAll(additionalResultMappings);
   List<XNode> resultChildren = resultMapNode.getChildren();
   for (XNode resultChild : resultChildren) {
     if ("constructor".equals(resultChild.getName())) {
       processConstructorElement(resultChild, typeClass, resultMappings);
     } else if ("discriminator".equals(resultChild.getName())) {
       discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
     } else {
       ArrayList<ResultFlag> flags = new ArrayList<ResultFlag>();
       if ("id".equals(resultChild.getName())) {
         flags.add(ResultFlag.ID);
       }
       resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
     }
   }
   ResultMapResolver resultMapResolver =
       new ResultMapResolver(
           builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
   try {
     return resultMapResolver.resolve();
   } catch (IncompleteElementException e) {
     configuration.addIncompleteResultMap(resultMapResolver);
     throw e;
   }
 }
 public void setParameters(PreparedStatement ps) throws SQLException {
   ErrorContext.instance()
       .activity("setting parameters")
       .object(mappedStatement.getParameterMap().getId());
   List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
   if (parameterMappings != null) {
     MetaObject metaObject =
         parameterObject == null ? null : configuration.newMetaObject(parameterObject);
     for (int i = 0; i < parameterMappings.size(); i++) {
       ParameterMapping parameterMapping = parameterMappings.get(i);
       if (parameterMapping.getMode() != ParameterMode.OUT) {
         Object value;
         String propertyName = parameterMapping.getProperty();
         if (boundSql.hasAdditionalParameter(
             propertyName)) { // issue #448 ask first for additional params
           value = boundSql.getAdditionalParameter(propertyName);
         } else if (parameterObject == null) {
           value = null;
         } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
           value = parameterObject;
         } else {
           value = metaObject == null ? null : metaObject.getValue(propertyName);
         }
         TypeHandler typeHandler = parameterMapping.getTypeHandler();
         if (typeHandler == null) {
           throw new ExecutorException(
               "There was no TypeHandler found for parameter "
                   + propertyName
                   + " of statement "
                   + mappedStatement.getId());
         }
         JdbcType jdbcType = parameterMapping.getJdbcType();
         if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
         typeHandler.setParameter(ps, i + 1, value, jdbcType);
       }
     }
   }
 }
  /**
   * Build a {@code SqlSessionFactory} instance.
   *
   * <p>The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
   * {@code SqlSessionFactory} instance based on an Reader.
   *
   * @return SqlSessionFactory
   * @throws IOException if loading the config file failed
   */
  protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configLocation != null) {
      xmlConfigBuilder =
          new XMLConfigBuilder(
              this.configLocation.getInputStream(), null, this.configurationProperties);
      configuration = xmlConfigBuilder.getConfiguration();
    } else {
      if (this.logger.isDebugEnabled()) {
        this.logger.debug(
            "Property 'configLocation' not specified, using default MyBatis Configuration");
      }
      configuration = new Configuration();
      configuration.setVariables(this.configurationProperties);
    }

    if (this.objectFactory != null) {
      configuration.setObjectFactory(this.objectFactory);
    }

    if (this.objectWrapperFactory != null) {
      configuration.setObjectWrapperFactory(this.objectWrapperFactory);
    }

    if (hasLength(this.typeAliasesPackage)) {
      String[] typeAliasPackageArray =
          tokenizeToStringArray(
              this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
      for (String packageToScan : typeAliasPackageArray) {
        configuration
            .getTypeAliasRegistry()
            .registerAliases(
                packageToScan, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Scanned package: '" + packageToScan + "' for aliases");
        }
      }
    }

    if (!isEmpty(this.typeAliases)) {
      for (Class<?> typeAlias : this.typeAliases) {
        configuration.getTypeAliasRegistry().registerAlias(typeAlias);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Registered type alias: '" + typeAlias + "'");
        }
      }
    }

    if (!isEmpty(this.plugins)) {
      for (Interceptor plugin : this.plugins) {
        configuration.addInterceptor(plugin);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Registered plugin: '" + plugin + "'");
        }
      }
    }

    if (hasLength(this.typeHandlersPackage)) {
      String[] typeHandlersPackageArray =
          tokenizeToStringArray(
              this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
      for (String packageToScan : typeHandlersPackageArray) {
        configuration.getTypeHandlerRegistry().register(packageToScan);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
        }
      }
    }

    if (!isEmpty(this.typeHandlers)) {
      for (TypeHandler<?> typeHandler : this.typeHandlers) {
        configuration.getTypeHandlerRegistry().register(typeHandler);
        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Registered type handler: '" + typeHandler + "'");
        }
      }
    }

    if (xmlConfigBuilder != null) {
      try {
        xmlConfigBuilder.parse();

        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Parsed configuration file: '" + this.configLocation + "'");
        }
      } catch (Exception ex) {
        throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
      } finally {
        ErrorContext.instance().reset();
      }
    }

    if (this.transactionFactory == null) {
      this.transactionFactory = new SpringManagedTransactionFactory();
    }

    Environment environment =
        new Environment(this.environment, this.transactionFactory, this.dataSource);
    configuration.setEnvironment(environment);

    if (this.databaseIdProvider != null) {
      try {
        configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
      } catch (SQLException e) {
        throw new NestedIOException("Failed getting a databaseId", e);
      }
    }

    ArrayList<Resource> listado_resources = new ArrayList<Resource>();

    if (!isEmpty(this.mapperLocations1)) {
      for (Resource resource : this.mapperLocations1) {
        listado_resources.add(resource);
      }
    }

    if (!isEmpty(this.mapperLocations2)) {
      for (Resource resource : this.mapperLocations2) {
        listado_resources.add(resource);
      }
    }

    if (!isEmpty(this.mapperLocations3)) {
      for (Resource resource : this.mapperLocations3) {
        listado_resources.add(resource);
      }
    }

    if (!isEmpty(this.mapperLocations4)) {
      for (Resource resource : this.mapperLocations4) {
        listado_resources.add(resource);
      }
    }

    this.mapperLocations = new Resource[listado_resources.size()];
    int index = 0;
    for (Resource resource : listado_resources) {
      this.mapperLocations[index] = resource;
      index++;
    }

    if (!isEmpty(this.mapperLocations)) {
      for (Resource mapperLocation : this.mapperLocations) {
        if (mapperLocation == null) {
          continue;
        }

        //				//log.info("Mapa cargado: " + mapperLocation);

        try {
          XMLMapperBuilder xmlMapperBuilder =
              new XMLMapperBuilder(
                  mapperLocation.getInputStream(),
                  configuration,
                  mapperLocation.toString(),
                  configuration.getSqlFragments());
          xmlMapperBuilder.parse();
        } catch (Exception e) {
          throw new NestedIOException(
              "Failed to parse mapping resource: '" + mapperLocation + "'", e);
        } finally {
          ErrorContext.instance().reset();
        }

        if (this.logger.isDebugEnabled()) {
          this.logger.debug("Parsed mapper file: '" + mapperLocation + "'");
        }
      }
    } else {
      if (this.logger.isDebugEnabled()) {
        this.logger.debug(
            "Property 'mapperLocations' was not specified or no matching resources found");
      }
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
  }
 public static RuntimeException wrapException(String message, Exception e) {
   return new PersistenceException(
       ErrorContext.instance().message(message).cause(e).toString(), e);
 }