Example usage for org.apache.ibatis.mapping Environment Environment

List of usage examples for org.apache.ibatis.mapping Environment Environment

Introduction

In this page you can find the example usage for org.apache.ibatis.mapping Environment Environment.

Prototype

public Environment(String id, TransactionFactory transactionFactory, DataSource dataSource) 

Source Link

Usage

From source file:cc.oit.dao.impl.mybatis.session.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 w  w w. j av  a 2 s. com*/
 * @throws java.io.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 = (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);
        }
    }

    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:com.aspectran.support.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./*from   ww  w  .j a  v  a  2 s. co  m*/
 *
 * @return SqlSessionFactory
 * @throws IOException if loading the config file failed
 */
protected SqlSessionFactory buildSqlSessionFactory(InputStream configLocationStream,
        InputStream[] mapperLocationStreams) throws IOException {
    Configuration configuration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (configLocationStream != null) {
        xmlConfigBuilder = new XMLConfigBuilder(configLocationStream, null, this.configurationProperties);
        configuration = xmlConfigBuilder.getConfiguration();
    } else {
        if (log.isDebugEnabled()) {
            log.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.hasLength(this.typeAliasesPackage)) {
        String[] typeAliasPackageArray = StringUtils.tokenize(this.typeAliasesPackage,
                CONFIG_LOCATION_DELIMITERS);
        for (String packageToScan : typeAliasPackageArray) {
            configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                    typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
            if (log.isDebugEnabled()) {
                log.debug("Scanned package: '" + packageToScan + "' for aliases");
            }
        }
    }

    if (this.typeAliases != null && this.typeAliases.length > 0) {
        for (Class<?> typeAlias : this.typeAliases) {
            configuration.getTypeAliasRegistry().registerAlias(typeAlias);
            if (log.isDebugEnabled()) {
                log.debug("Registered type alias: '" + typeAlias + "'");
            }
        }
    }

    if (this.plugins != null && this.plugins.length > 0) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            if (log.isDebugEnabled()) {
                log.debug("Registered plugin: '" + plugin + "'");
            }
        }
    }

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

    if (this.typeHandlers != null && this.typeHandlers.length > 0) {
        for (TypeHandler<?> typeHandler : this.typeHandlers) {
            configuration.getTypeHandlerRegistry().register(typeHandler);
            if (log.isDebugEnabled()) {
                log.debug("Registered type handler: '" + typeHandler + "'");
            }
        }
    }

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

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

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

    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 IllegalArgumentException("Failed getting a databaseId", e);
        }
    }

    if (mapperLocationStreams != null && mapperLocationStreams.length > 0) {
        for (int i = 0; i < mapperLocationStreams.length; i++) {
            if (mapperLocationStreams[i] == null) {
                continue;
            }

            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocationStreams[i],
                        configuration, mapperLocations[i], configuration.getSqlFragments());
                xmlMapperBuilder.parse();
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "Failed to parse mapping resource: '" + mapperLocations[i] + "'", e);
            } finally {
                ErrorContext.instance().reset();
            }

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

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:com.baidu.oped.apm.plugin.mybatis.SqlSessionTemplateIT.java

License:Apache License

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    Configuration configuration = mock(Configuration.class);
    TransactionFactory transactionFactory = mock(TransactionFactory.class);
    DataSource dataSource = mock(DataSource.class);
    Environment environment = new Environment("test", transactionFactory, dataSource);
    when(configuration.getEnvironment()).thenReturn(environment);
    when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration);
    when(this.sqlSessionFactory.openSession(EXECUTOR_TYPE)).thenReturn(this.sqlSessionProxy);
    this.sqlSessionTemplate = new SqlSessionTemplate(this.sqlSessionFactory, EXECUTOR_TYPE);
}

From source file:com.baidu.oped.apm.profiler.modifier.orm.mybatis.SqlSessionTemplateModifierTest.java

License:Apache License

private void setUpSqlSessionFactory() throws Exception {
    Configuration configuration = mock(Configuration.class);
    TransactionFactory transactionFactory = mock(TransactionFactory.class);
    DataSource dataSource = mock(DataSource.class);
    Environment environment = new Environment("test", transactionFactory, dataSource);
    when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration);
    when(configuration.getEnvironment()).thenReturn(environment);
}

From source file:com.baifendian.swordfish.dao.datasource.ConnectionFactory.java

License:Apache License

/**
 *  sql session factory/* w w w  . j  a v  a  2 s . co m*/
 */
public static SqlSessionFactory getSqlSessionFactory() {
    if (sqlSessionFactory == null) {
        synchronized (ConnectionFactory.class) {
            if (sqlSessionFactory == null) {
                DataSource dataSource = getDataSource();
                TransactionFactory transactionFactory = new JdbcTransactionFactory();

                Environment environment = new Environment("development", transactionFactory, dataSource);

                Configuration configuration = new Configuration(environment);
                configuration.setLazyLoadingEnabled(true);
                configuration.addMappers("com.baifendian.swordfish.dao.mapper");

                SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
                sqlSessionFactory = builder.build(configuration);
            }
        }
    }

    return sqlSessionFactory;
}

From source file:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean.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//from   w ww  .  java 2  s . co m
 * @throws IOException if loading the config file failed
 */
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;

    // TODO  MybatisXmlConfigBuilder
    MybatisXMLConfigBuilder 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 MybatisXMLConfigBuilder(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");
        }
        // TODO ?
        configuration = new MybatisConfiguration();
        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)) {
        // TODO ??
        String[] typeAliasPackageArray;
        if (typeAliasesPackage.contains("*")) {
            typeAliasPackageArray = PackageHelper.convertTypeAliasesPackage(typeAliasesPackage);
        } else {
            typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        }
        if (typeAliasPackageArray == null) {
            throw new MybatisPlusException("not find typeAliasesPackage:" + 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 (!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));
    // ?
    GlobalConfiguration.setMetaData(dataSource, globalConfig);
    SqlSessionFactory sqlSessionFactory = this.sqlSessionFactoryBuilder.build(configuration);
    // TODO SqlRunner
    SqlRunner.FACTORY = sqlSessionFactory;
    // TODO  sqlSessionFactory
    globalConfig.setSqlSessionFactory(sqlSessionFactory);
    // TODO ?
    globalConfig.signGlobalConfig(sqlSessionFactory);

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

            try {
                // TODO
                MybatisXMLMapperBuilder xmlMapperBuilder = new MybatisXMLMapperBuilder(
                        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 sqlSessionFactory;
}

From source file:com.bolo.orm.mybatis.SqlSessionFactoryBean.java

License:Apache License

/**
 * Build a {@code SqlSessionFactory} instance.
 * /*from www .  ja  va  2  s .com*/
 * 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 (hasLength(this.typeAliasesPackage)) {
        String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

        /*
         * ?typeAliasPackageArray???
         * 
         * @author wangmb
         * 
         * @date 2012-08-22
         */
        typeAliasPackageArray = new Scanner().doScan(typeAliasPackageArray);

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

    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:com.codyy.data.sqlparse.OlapSqlSessionFactory.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//w  ww.  j  a v  a2 s . co  m
 * @throws IOException if loading the config file failed
 */
protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

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

    BasicDataSource dataSource = new BasicDataSource();
    Environment environment = new Environment(this.environment, this.transactionFactory, 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);
    //      }
    //    }

    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:com.dmm.framework.basedb.mybatis.spring.SqlSessionFactoryBean.java

License:Apache License

/**
 * Build a {@code SqlSessionFactory} instance.
 * //from  w w  w  . j a  va2  s. c o  m
 * 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 com.dmm.framework.basedb.apache.ibatis.thread.Runnable(location, configuration).run();

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:com.dvdprime.server.mobile.config.MyBatisConfig.java

License:Apache License

/**
 * MyBatis ?  Configuration? ./*from  ww  w  .j  a  v  a 2s  .  co  m*/
 * 
 * @return
 */
public Configuration getConfig() {
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    Environment environment = new Environment("master", transactionFactory, getTomcatDataSource());

    logger.info("MyBatis Configuration Initialization.");
    Configuration configuration = new Configuration(environment);
    configuration.setCacheEnabled(true);
    configuration.setLazyLoadingEnabled(false);
    configuration.setAggressiveLazyLoading(false);
    configuration.setUseColumnLabel(true);
    configuration.setUseGeneratedKeys(false);
    configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);
    configuration.setDefaultExecutorType(ExecutorType.REUSE);
    configuration.setDefaultStatementTimeout(25000);
    configuration.setSafeRowBoundsEnabled(true);

    // Alias Type
    Iterator<String> it = TypeAliasProp.getProperties().keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        logger.info("typeAliasRegistry: [{}] -> [{}]", key, TypeAliasProp.getProperties().get(key));
        configuration.getTypeAliasRegistry().registerAlias(key,
                (String) TypeAliasProp.getProperties().get(key));
    }

    // Mapper
    it = MapperProp.getProperties().keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        logger.info("mapper loaded: [{}]", MapperProp.getProperties().get(key));
        try {
            InputStream inputStream = Resources
                    .getResourceAsStream((String) MapperProp.getProperties().get(key));
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration,
                    (String) MapperProp.getProperties().get(key), configuration.getSqlFragments());
            mapperParser.parse();
        } catch (IOException e) {
            logger.error("mapper parsing   ?.");
        }
    }

    return configuration;
}