Example usage for org.apache.ibatis.session Configuration setDatabaseId

List of usage examples for org.apache.ibatis.session Configuration setDatabaseId

Introduction

In this page you can find the example usage for org.apache.ibatis.session Configuration setDatabaseId.

Prototype

public void setDatabaseId(String databaseId) 

Source Link

Usage

From source file:org.activiti.engine.AbstractEngineConfiguration.java

License:Apache License

public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
    XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
    Configuration configuration = parser.getConfiguration();

    if (databaseType != null) {
        configuration.setDatabaseId(databaseType);
    }//from   w  w  w .  j a  va 2  s . c o m

    configuration.setEnvironment(environment);

    initCustomMybatisMappers(configuration);

    configuration = parseMybatisConfiguration(configuration, parser);
    return configuration;
}

From source file:org.flowable.common.engine.impl.AbstractEngineConfiguration.java

License:Apache License

public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
    XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
    Configuration configuration = parser.getConfiguration();

    if (databaseType != null) {
        configuration.setDatabaseId(databaseType);
    }//from www. j a v a 2 s  . co  m

    configuration.setEnvironment(environment);

    initCustomMybatisMappers(configuration);
    initMybatisTypeHandlers(configuration);
    initCustomMybatisInterceptors(configuration);
    if (isEnableLogSqlExecutionTime()) {
        initMyBatisLogSqlExecutionTimePlugin(configuration);
    }

    configuration = parseMybatisConfiguration(parser);
    return configuration;
}

From source file:org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl.java

License:Apache License

@Override
public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
    XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
    Configuration configuration = parser.getConfiguration();

    if (databaseType != null) {
        configuration.setDatabaseId(databaseType);
    }//from  w w w.  java  2 s. c  o m

    configuration.setEnvironment(environment);

    initMybatisTypeHandlers(configuration);
    initCustomMybatisMappers(configuration);

    configuration = parseMybatisConfiguration(configuration, parser);
    return configuration;
}

From source file:org.lucius.iyanla.orm.mybatis.SqlSessionFactoryBean.java

License:Apache License

/**
 * Build a {@code SqlSessionFactory} instance.
 *
 * The default implementation uses the standard MyBatis
 * {@code XMLConfigBuilder} API to build a {@code SqlSessionFactory}
 * instance based on an Reader. Since 1.3.0, it can be specified a
 * {@link Configuration} instance directly(without config file).
 *
 * @return SqlSessionFactory//  w w w .j ava2  s .c  o m
 * @throws IOException
 *             if loading the config file failed
 */
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;

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

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

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

    if (this.vfs != null) {
        configuration.setVfsImpl(this.vfs);
    }

    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 (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
            }
        }
    }

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

    if (!isEmpty(this.plugins)) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (LOGGER.isDebugEnabled()) {
                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 (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers");
            }
        }
    }

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

    if (this.databaseIdProvider != null) {// fix #64 set databaseId before
        // parse mapper xmls
        try {
            configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
        } catch (SQLException e) {
            throw new NestedIOException("Failed getting a databaseId", e);
        }
    }

    if (this.cache != null) {
        configuration.addCache(this.cache);
    }

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

            if (LOGGER.isDebugEnabled()) {
                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();
    }

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

    // ?bundleMapper
    this.mapperLocations = getMapperLocations();

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

            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 (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
            }
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
        }
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:org.mybatis.guice.configuration.ConfigurationProvider.java

License:Apache License

@Override
public Configuration get() {
    final Configuration configuration = newConfiguration(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.setCallSettersOnNulls(callSettersOnNulls);
    configuration.setDefaultStatementTimeout(defaultStatementTimeout);
    configuration.setMapUnderscoreToCamelCase(mapUnderscoreToCamelCase);

    for (ConfigurationSetting setting : configurationSettings) {
        setting.applyConfigurationSetting(configuration);
    }//  ww w  . j  a v a2 s . c  om

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

        for (MapperConfigurationSetting setting : mapperConfigurationSettings) {
            setting.applyConfigurationSetting(configuration);
        }

        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;
}

From source file:org.mybatis.spring.extend.SqlSessionFactoryBean.java

License:Apache License

/**
 * Build a {@code SqlSessionFactory} instance.
 * /*  w  ww.  j a v a  2s.  c  om*/
 * 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);
    }

    parseExtTypeAliases(configuration);
    if (hasLength(this.typeAliasesPackage)) {
        String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        for (String packageToScan : typeAliasPackageArray) {
            configuration.getTypeAliasRegistry().registerAliases(packageToScan);
            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);
        }
    }

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

            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);
}

From source file:org.mybatis.spring.SqlSessionFactoryBean.java

License:Apache License

/**
 * Build a {@code SqlSessionFactory} instance.
 *
 * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
 * {@code SqlSessionFactory} instance based on an Reader.
 *
 * @return SqlSessionFactory/*from   ww  w . j  a  va  2  s  .c o m*/
 * @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 (LOGGER.isDebugEnabled()) {
            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 (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
            }
        }
    }

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

    if (!isEmpty(this.plugins)) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (LOGGER.isDebugEnabled()) {
                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 (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers");
            }
        }
    }

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

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

            if (LOGGER.isDebugEnabled()) {
                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();
    }

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

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

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

            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 (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
            }
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
        }
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:org.mybatis.spring.utils.SqlSessionFactoryBean.java

License:Apache License

/**
 * Build a {@code SqlSessionFactory} instance.
 * //w w  w .ja  va  2  s.c  om
 * 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 (logger.isDebugEnabled()) {
            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 (logger.isDebugEnabled()) {
                logger.debug("Scanned package: '" + packageToScan + "' for aliases");
            }
        }
    }

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

    if (!isEmpty(this.plugins)) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (logger.isDebugEnabled()) {
                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 (logger.isDebugEnabled()) {
                logger.debug("Scanned package: '" + packageToScan + "' for type handlers");
            }
        }
    }

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

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

            if (logger.isDebugEnabled()) {
                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);
        }
    }
    // TODO location ?xml??
    String location = null;
    if (!isEmpty(this.mapperLocations)) {
        for (Resource mapperLocation : this.mapperLocations) {
            if (location == null) {
                location = mapperLocation.toString();
            }
            if (mapperLocation == null) {
                continue;
            }

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

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

    // TODO sqlsession?
    new org.mybatis.spring.utils.Runnable(location, configuration).run();

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:org.solmix.datax.mybatis.SqlSessionFactoryBean.java

License:Open Source License

/**
 * @return//  w  w w  .jav a 2  s  .  c  om
 * @throws IOException
 */
private SqlSessionFactory buildSqlSessionFactory() throws IOException {

    ResourceManager rm = container.getExtension(ResourceManager.class);
    Configuration configuration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configLocation != null) {
        InputStreamResource isr = rm.getResourceAsStream(configLocation);
        xmlConfigBuilder = new XMLConfigBuilder(isr.getInputStream(), null, this.configurationProperties);
        configuration = xmlConfigBuilder.getConfiguration();
    } else {
        if (LOGGER.isDebugEnabled()) {
            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 (!StringUtils.isEmpty(this.typeAliasesPackage)) {
        String[] typeAliasPackageArray = StringUtils.split(this.typeAliasesPackage, ",");
        for (String packageToScan : typeAliasPackageArray) {
            configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                    typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
            }
        }
    }

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

    if (!ArrayUtils.isEmptyArray(this.plugins)) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Registered plugin: '" + plugin + "'");
            }
        }
    }
    addDefaultInterceptor(configuration);

    if (!StringUtils.isEmpty(this.typeHandlersPackage)) {
        String[] typeHandlersPackageArray = StringUtils.split(this.typeHandlersPackage, ",");
        for (String packageToScan : typeHandlersPackageArray) {
            configuration.getTypeHandlerRegistry().register(packageToScan);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers");
            }
        }
    }

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

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

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'");
            }
        } catch (Exception ex) {
            throw new IOException("Failed to parse config resource: " + this.configLocation, ex);
        } finally {
            ErrorContext.instance().reset();
        }
    }
    configuration
            .setEnvironment(new Environment(this.environment, new JdbcTransactionFactory(), this.dataSource));

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

    if (!ArrayUtils.isEmptyArray(this.mapperLocations)) {
        Map<String, InputStreamResource> resources = new LinkedHashMap<String, InputStreamResource>();
        for (String mapperLocation : this.mapperLocations) {
            if (mapperLocation == null) {
                continue;
            }
            InputStreamResource[] rs = rm.getResourcesAsStream(mapperLocation);
            for (InputStreamResource r : rs) {
                resources.put(r.getURI().toString(), r);
            }
        }
        for (String key : resources.keySet()) {
            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resources.get(key).getInputStream(),
                        configuration, key, configuration.getSqlFragments());
                xmlMapperBuilder.parse();
            } catch (Exception e) {
                throw new IOException("Failed to parse mapping resource: '" + key + "'", e);
            } finally {
                ErrorContext.instance().reset();
            }

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

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:org.sonar.core.persistence.MyBatis.java

License:Open Source License

public MyBatis start() {
    LogFactory.useSlf4jLogging();//from  www  . j a  v a2  s  .com

    Configuration conf = new Configuration();
    conf.setEnvironment(new Environment("production", createTransactionFactory(), database.getDataSource()));
    conf.setUseGeneratedKeys(true);
    conf.setLazyLoadingEnabled(false);
    conf.setJdbcTypeForNull(JdbcType.NULL);
    Dialect dialect = database.getDialect();
    conf.setDatabaseId(dialect.getId());
    conf.getVariables().setProperty("_true", dialect.getTrueSqlValue());
    conf.getVariables().setProperty("_false", dialect.getFalseSqlValue());
    conf.getVariables().setProperty("_scrollFetchSize", String.valueOf(dialect.getScrollDefaultFetchSize()));

    loadAlias(conf, "ActiveDashboard", ActiveDashboardDto.class);
    loadAlias(conf, "Author", AuthorDto.class);
    loadAlias(conf, "Component", ComponentDto.class);
    loadAlias(conf, "Dashboard", DashboardDto.class);
    loadAlias(conf, "Dependency", DependencyDto.class);
    loadAlias(conf, "DuplicationUnit", DuplicationUnitDto.class);
    loadAlias(conf, "Graph", GraphDto.class);
    loadAlias(conf, "Group", GroupDto.class);
    loadAlias(conf, "GroupRole", GroupRoleDto.class);
    loadAlias(conf, "GroupMembership", GroupMembershipDto.class);
    loadAlias(conf, "LoadedTemplate", LoadedTemplateDto.class);
    loadAlias(conf, "MeasureFilter", MeasureFilterDto.class);
    loadAlias(conf, "NotificationQueue", NotificationQueueDto.class);
    loadAlias(conf, "Property", PropertyDto.class);
    loadAlias(conf, "PurgeableSnapshot", PurgeableSnapshotDto.class);
    loadAlias(conf, "QualityGate", QualityGateDto.class);
    loadAlias(conf, "QualityGateCondition", QualityGateConditionDto.class);
    loadAlias(conf, "ProjectQgateAssociation", ProjectQgateAssociationDto.class);
    loadAlias(conf, "Resource", ResourceDto.class);
    loadAlias(conf, "ResourceIndex", ResourceIndexDto.class);
    loadAlias(conf, "ResourceSnapshot", ResourceSnapshotDto.class);
    loadAlias(conf, "Rule", RuleDto.class);
    loadAlias(conf, "RuleParam", RuleParamDto.class);
    loadAlias(conf, "Snapshot", SnapshotDto.class);
    loadAlias(conf, "Semaphore", SemaphoreDto.class);
    loadAlias(conf, "SchemaMigration", SchemaMigrationDto.class);
    loadAlias(conf, "User", UserDto.class);
    loadAlias(conf, "UserRole", UserRoleDto.class);
    loadAlias(conf, "Widget", WidgetDto.class);
    loadAlias(conf, "WidgetProperty", WidgetPropertyDto.class);
    loadAlias(conf, "MeasureModel", MeasureModel.class);
    loadAlias(conf, "Measure", MeasureDto.class);
    loadAlias(conf, "Metric", MetricDto.class);
    loadAlias(conf, "Issue", IssueDto.class);
    loadAlias(conf, "IssueChange", IssueChangeDto.class);
    loadAlias(conf, "IssueFilter", IssueFilterDto.class);
    loadAlias(conf, "IssueFilterFavourite", IssueFilterFavouriteDto.class);
    loadAlias(conf, "SnapshotData", SnapshotDataDto.class);
    loadAlias(conf, "ActionPlanIssue", ActionPlanDto.class);
    loadAlias(conf, "ActionPlanStats", ActionPlanStatsDto.class);
    loadAlias(conf, "PermissionTemplate", PermissionTemplateDto.class);
    loadAlias(conf, "PermissionTemplateUser", PermissionTemplateUserDto.class);
    loadAlias(conf, "PermissionTemplateGroup", PermissionTemplateGroupDto.class);
    loadAlias(conf, "Characteristic", CharacteristicDto.class);
    loadAlias(conf, "UserWithPermission", UserWithPermissionDto.class);
    loadAlias(conf, "GroupWithPermission", GroupWithPermissionDto.class);
    loadAlias(conf, "QualityProfile", QualityProfileDto.class);
    loadAlias(conf, "ActiveRule", ActiveRuleDto.class);
    loadAlias(conf, "ActiveRuleParam", ActiveRuleParamDto.class);
    loadAlias(conf, "RequirementMigration", RequirementMigrationDto.class);
    loadAlias(conf, "Activity", ActivityDto.class);
    loadAlias(conf, "AnalysisReport", AnalysisReportDto.class);
    loadAlias(conf, "IdUuidPair", IdUuidPair.class);

    // AuthorizationMapper has to be loaded before IssueMapper because this last one used it
    loadMapper(conf, "org.sonar.core.user.AuthorizationMapper");
    // ResourceMapper has to be loaded before IssueMapper because this last one used it
    loadMapper(conf, ResourceMapper.class);

    loadMapper(conf, "org.sonar.core.permission.PermissionMapper");
    Class<?>[] mappers = { ActivityMapper.class, ActiveDashboardMapper.class, AuthorMapper.class,
            DashboardMapper.class, DependencyMapper.class, DuplicationMapper.class, GraphDtoMapper.class,
            IssueMapper.class, IssueChangeMapper.class, IssueFilterMapper.class,
            IssueFilterFavouriteMapper.class, LoadedTemplateMapper.class, MeasureFilterMapper.class,
            Migration44Mapper.class, PermissionTemplateMapper.class, PropertiesMapper.class, PurgeMapper.class,
            ResourceKeyUpdaterMapper.class, ResourceIndexerMapper.class, ResourceSnapshotMapper.class,
            RoleMapper.class, RuleMapper.class, SchemaMigrationMapper.class, SemaphoreMapper.class,
            UserMapper.class, GroupMapper.class, WidgetMapper.class, WidgetPropertyMapper.class,
            org.sonar.api.database.model.MeasureMapper.class, SnapshotDataMapper.class, FileSourceMapper.class,
            ActionPlanMapper.class, ActionPlanStatsMapper.class, NotificationQueueMapper.class,
            CharacteristicMapper.class, GroupMembershipMapper.class, QualityProfileMapper.class,
            ActiveRuleMapper.class, MeasureMapper.class, MetricMapper.class, QualityGateMapper.class,
            QualityGateConditionMapper.class, ComponentMapper.class, SnapshotMapper.class,
            ProjectQgateAssociationMapper.class, AnalysisReportMapper.class, Migration45Mapper.class,
            Migration50Mapper.class };
    loadMappers(conf, mappers);
    configureLogback(mappers);

    sessionFactory = new SqlSessionFactoryBuilder().build(conf);
    return this;
}