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

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

Introduction

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

Prototype

public void setEnvironment(Environment environment) 

Source Link

Usage

From source file:org.pssframework.dao.SqlSessionFactoryFactoryBean.java

License:Open Source License

private SqlSessionFactory createSqlSessionFactory() throws IOException {
    Reader reader = new InputStreamReader(getConfigLocation().getInputStream());
    try {/* ww w . j av  a  2  s  .  c  o m*/
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        Configuration conf = sqlSessionFactory.getConfiguration();
        if (dataSource != null) {
            DataSource dataSourceToUse = this.dataSource;
            if (this.useTransactionAwareDataSource
                    && !(this.dataSource instanceof TransactionAwareDataSourceProxy)) {
                dataSourceToUse = new TransactionAwareDataSourceProxy(this.dataSource);
            }

            conf.setEnvironment(
                    new Environment("development", new ManagedTransactionFactory(), dataSourceToUse));
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(conf);
        }

        if (mapperLocations != null) {
            Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
            for (Resource r : mapperLocations) {
                logger.info("Loading iBatis3 mapper xml from file[" + r.getFile().getAbsolutePath() + "]");

                Reader mapperReader = new InputStreamReader(r.getInputStream());
                try {
                    XMLMapperBuilder mapperBuilder = new XMLMapperBuilder(mapperReader, conf,
                            r.getFile().getAbsolutePath(), sqlFragments);
                    mapperBuilder.parse();
                } finally {
                    mapperReader.close();
                }
            }
        }
        return sqlSessionFactory;
    } finally {
        reader.close();
    }
}

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

License:Open Source License

/**
 * @return/*w w w. j  a  va 2  s .co m*/
 * @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();/* www  .  ja v  a  2 s.  c o m*/

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

From source file:paner.das.strong.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 ww  .j  av  a 2  s . c om
 * @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) {
            // ThinkGem ???????
            try {
                configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                        typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
            } catch (Exception ex) {
                LOGGER.error("Scanned package: '" + packageToScan + "' for aliases", ex);
                throw new NestedIOException("Scanned package: '" + packageToScan + "' for aliases", ex);
            } finally {
                ErrorContext.instance().reset();
            }
            // ThinkGem end
            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) {
                // ThinkGem MapperXML????
                LOGGER.error("Failed to parse mapping resource: '" + mapperLocation + "'", e);
                throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
            } finally {
                ErrorContext.instance().reset();
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
            }
        }

        // ThinkGem ?MapperXML?
        //new MapperRefreshThread(this.mapperLocations, configuration).run();
        this.mapperRefresh.setConfiguration(configuration);

    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
        }
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
}

From source file:uap.workflow.engine.cfg.ProcessEngineConfigurationImpl.java

License:Apache License

@SuppressWarnings("deprecation")
protected void initSqlSessionFactory() {
    if (sqlSessionFactory == null) {
        InputStream inputStream = null;
        try {//w ww  .  jav  a  2 s  .  c o  m
            inputStream = ReflectUtil.getResourceAsStream("org/activiti/db/mapping/mappings.xml");
            if (inputStream == null)
                return;
            // update the jdbc parameters to the configured ones...
            Environment environment = new Environment("default", transactionFactory, dataSource);
            Reader reader = new InputStreamReader(inputStream);
            XMLConfigBuilder parser = new XMLConfigBuilder(reader);
            Configuration configuration = parser.getConfiguration();
            configuration.setEnvironment(environment);
            configuration.getTypeHandlerRegistry().register(VariableType.class, JdbcType.VARCHAR,
                    new IbatisVariableTypeHandler());
            //configuration = parser.parse();
            sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        } catch (Exception e) {
            throw new WorkflowException("Error while building ibatis SqlSessionFactory: " + e.getMessage(), e);
        } finally {
            IoUtil.closeSilently(inputStream);
        }
    }
}