IBatis - Choosing an Environment Using XML

I have this configuration in ibatis-config.xml

<configuration>
    <properties resource="collector.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${dev.jdbc.driver}" />
                <property name="url" value="${dev.jdbc.url}" />
            </dataSource>
        </environment>
        <environment id="test">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${test.jdbc.driver}" />
                <property name="url" value="${test.jdbc.url}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
    </mappers>
</configuration>

As shown, it will load the data source from <environment id="development">

QUESTION : Is it possible to use a switch at run time <environment id="test">without changing XML? For example, I have a test file where I use SqlSessionFactoryand want it to use the test environment programmatically?

+3
source share
2 answers

The SqlSessionFactoryBuilder.build () method can select a specific environment in XML.

For instance,

private Reader reader;
private SqlSessionFactory sqlSessionFactorys;
private SqlSession session;

reader = Resources.getResourceAsReader("ibatis-config.xml");

sqlSessionFactorys = new SqlSessionFactoryBuilder().build(reader, "test");
testSession = sqlSessionFactorys.openSession(); // test env

sqlSessionFactorys = new SqlSessionFactoryBuilder().build(reader, "development");
devSession = sqlSessionFactorys.openSession(); // dev env
+7
source

: http://codenav.org/code.html?project=/org/mybatis/mybatis/3.2.5&path=/Source%20Packages/org.apache.ibatis.session/SqlSessionFactoryBuilder.java

build() / SqlSessionFactory. /, . , / . , bean factory - ().

.

try {
    inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG_PATH);
    prodDbSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, prodDbEnvironment);
    inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG_PATH);
    securityDbSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, securityDbEnvironment);
} catch (IOException ex) {
    String msg = "Unable to get SqlSessionFactory";
    CustomizedLogger.LOG(Level.SEVERE, this.getClass().getCanonicalName(), "methodName", msg, ex);
}

catch catch, , .

, .

: Java EE MyBatis , , . JPA , .

+2

Source: https://habr.com/ru/post/1741353/


All Articles