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: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 ww . j  a  va2  s .c om
 * @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.ConfigurationProviderTest.java

License:Apache License

@BeforeEach
public void beforeTest() {
    environment = new Environment("test", transactionFactory, dataSource);
    configurationProvider = new ConfigurationProvider(environment);
}

From source file:org.mybatis.guice.environment.EnvironmentProvider.java

License:Apache License

/**
 * {@inheritDoc}
 */
@Override
public Environment get() {
    return new Environment(id, transactionFactory, dataSource);
}

From source file:org.mybatis.scripting.freemarker.CustomizedDataContextTest.java

License:Apache License

@BeforeAll
public static void setUp() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");

    JDBCDataSource dataSource = new JDBCDataSource();
    dataSource.setUrl("jdbc:hsqldb:mem:db4");
    dataSource.setUser("sa");
    dataSource.setPassword("");

    try (Connection conn = dataSource.getConnection()) {
        try (Reader reader = Resources.getResourceAsReader("org/mybatis/scripting/freemarker/create-db.sql")) {
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setLogWriter(null);/*from  w w  w .  ja  v  a  2 s . c  o m*/
            runner.setErrorLogWriter(null);
            runner.runScript(reader);
            conn.commit();
        }
    }

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

    // You can call configuration.setDefaultScriptingLanguage(FreeMarkerLanguageDriver.class)
    // after this to use FreeMarker driver by default.
    Configuration configuration = new Configuration(environment);

    configuration.addMapper(CustomizedDataContextMapper.class);
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}

From source file:org.mybatis.scripting.freemarker.FreeMarkerInAnnotationsTest.java

License:Apache License

@BeforeAll
public static void setUp() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");

    JDBCDataSource dataSource = new JDBCDataSource();
    dataSource.setUrl("jdbc:hsqldb:mem:db1");
    dataSource.setUser("sa");
    dataSource.setPassword("");

    try (Connection conn = dataSource.getConnection()) {
        try (Reader reader = Resources.getResourceAsReader("org/mybatis/scripting/freemarker/create-db.sql")) {
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setLogWriter(null);/*ww w  .  j a  v a  2  s .  c o  m*/
            runner.setErrorLogWriter(null);
            runner.runScript(reader);
            conn.commit();
        }
    }

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

    // You can call configuration.setDefaultScriptingLanguage(FreeMarkerLanguageDriver.class)
    // after this to use FreeMarker driver by default.
    Configuration configuration = new Configuration(environment);

    configuration.addMapper(NameMapper.class);
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}

From source file:org.mybatis.scripting.freemarker.PreparedParamsTest.java

License:Apache License

@BeforeAll
public static void setUp() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");

    JDBCDataSource dataSource = new JDBCDataSource();
    dataSource.setUrl("jdbc:hsqldb:mem:db3");
    dataSource.setUser("sa");
    dataSource.setPassword("");

    try (Connection conn = dataSource.getConnection()) {
        try (Reader reader = Resources.getResourceAsReader("org/mybatis/scripting/freemarker/create-db.sql")) {
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setLogWriter(null);//  ww w  .ja  v  a 2  s .c om
            runner.setErrorLogWriter(null);
            runner.runScript(reader);
            conn.commit();
        }
    }

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

    // You can call configuration.setDefaultScriptingLanguage(FreeMarkerLanguageDriver.class)
    // after this to use FreeMarker driver by default.
    Configuration configuration = new Configuration(environment);

    configuration.addMapper(PreparedParamsMapper.class);
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}

From source file:org.mybatis.spring.batch.builder.MyBatisBatchItemWriterBuilderTest.java

License:Apache License

@BeforeEach
void setUp() {//from   w w w .j av a 2s .  co  m
    MockitoAnnotations.initMocks(this);
    {
        Configuration configuration = new Configuration();
        Environment environment = new Environment("unittest", new JdbcTransactionFactory(), dataSource);
        configuration.setEnvironment(environment);
        Mockito.when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration);
        Mockito.when(this.sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(this.sqlSession);
    }
    {
        BatchResult result = new BatchResult(null, null);
        result.setUpdateCounts(new int[] { 1 });
        Mockito.when(this.sqlSession.flushStatements()).thenReturn(Collections.singletonList(result));
    }
}

From source file:org.mybatis.spring.batch.builder.MyBatisPagingItemReaderBuilderTest.java

License:Apache License

@BeforeEach
void setUp() {/*from  w ww  .  j av  a2 s. c om*/
    MockitoAnnotations.initMocks(this);

    Configuration configuration = new Configuration();
    Environment environment = new Environment("unittest", new JdbcTransactionFactory(), dataSource);
    configuration.setEnvironment(environment);
    Mockito.when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration);
    Mockito.when(this.sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(this.sqlSession);
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("id", 1);
    parameters.put("_page", 0);
    parameters.put("_pagesize", 10);
    parameters.put("_skiprows", 0);
    Mockito.when(this.sqlSession.selectList("selectFoo", parameters)).thenReturn(getFoos());
}

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

License:Apache License

/**
 * Build a {@code SqlSessionFactory} instance.
 * //w w  w  .  j  a v  a  2 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 (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.mapper.MapperFactoryBeanTest.java

License:Apache License

@Test
public void testWithNonSpringTransactionFactory() throws Exception {
    Environment original = sqlSessionFactory.getConfiguration().getEnvironment();
    Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), dataSource);
    sqlSessionFactory.getConfiguration().setEnvironment(nonSpring);

    try {/*  ww  w  .ja v  a 2s . c o  m*/
        find(new SqlSessionTemplate(sqlSessionFactory));

        assertCommit(); // SqlSessionTemplate autocommits
        assertCommitSession();
        assertSingleConnection();
        assertExecuteCount(1);
    } finally {
        sqlSessionFactory.getConfiguration().setEnvironment(original);
    }
}