Environment iBatis-使用XML选择环境
我在Environment iBatis-使用XML选择环境,environment,ibatis,xml-configuration,Environment,Ibatis,Xml Configuration,我在ibatis config.xml <configuration> <properties resource="collector.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" />
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>
如图所示,它将从
问题:在运行时开关是否可以在不修改XML的情况下使用
?例如,我有一个测试文件,其中我正在使用SqlSessionFactory
,并希望通过编程将其设置为使用测试环境?SqlSessionFactoryBuilder.build()方法可以选择XML中的特定环境
比如说,
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
根据该网站:
build()
方法在立即返回SqlSessionFactory之前关闭读卡器/inputstream。因此,您需要打开一个新的读卡器/流才能加载第二个会话。当我将帐户/安全表从主应用程序数据库分离到一个单独的数据库时,我发现了这一点。在我的第一次尝试中,由于输入流错误(已关闭),当bean尝试加载会话工厂时,我不断收到错误
e、 g
尽管我将它们放在单独的try-catch块中,以便我知道哪一个在日志文件中直接失败
我还将其作为一个单例实现,这样它只需加载一次资源
上下文:我在一个JavaEE容器中运行它,并使用MyBatis进行直接查询,在这里我将使用本机查询,因为它是一个更简单和直接的框架。我可能会在任何地方使用它而不是JPA,但这仍有待讨论 亚历克斯-穆查斯·格雷西亚斯!我正准备在这里发布您自己的邮件列表中的答案:)理想情况下,您应该使用构建工具和项目结构,这样就不会出现问题。我推荐maven,一开始它可能会有点混乱和神奇,但当你通过它时,它将节省大量的时间并实施一些好的实践。
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);
}