2013-02-21 104 views
2

我在我的应用程序中使用MyBatis和Spring Integration。我们公司有几个Oracle数据库。一个查询必须在一个数据库中执行,另一个必须在其他数据库中执行。如何配置MyBatis以将不同的数据库连接用于不同的查询?如何使用MyBatis Spring集成连接到多个数据库?

回答

3

我找到答案here。这种解决方案在某些情况下不是最好的,但对我有好处。

0

这是MyBatis 3用户指南中第一个主题。基本上你应该有几个XML配置文件为每个数据库。而最简单的方法是通过将配置

String resource = "org/mybatis/example/Configuration.xml"; 
Reader reader = Resources.getResourceAsReader(resource); 
sqlMapper = new SqlSessionFactoryBuilder().build(reader); 

编辑创建映射器: 对不起,没有仔细阅读。无论如何,我相信代码snipet是自我解释:

<jee:jndi-lookup id="jndiDatabase1"    jndi-name="jdbc/database1"/> 
<jee:jndi-lookup id="jndiDatabase2"    jndi-name="jdbc/database2"/> 

<bean id="database1" class="org.mybatis.spring.SqlSessionFactoryBean"> 
    <property name="configLocation"  value="classpath:/some/path/to/database1Config.xml"/> 
    <property name="dataSource"   ref="jndiDatabase1"/> 
</bean> 

<bean id="database2" class="org.mybatis.spring.SqlSessionFactoryBean"> 
    <property name="configLocation"  value="classpath:/some/path/to/database2Config.xml"/> 
    <property name="dataSource"   ref="jndiDatabase2"/> 
</bean> 
+0

配置它,我用的MyBatis Spring配置和我的代码不包含Java代码什么创造MyBatis的对象。这是我如何配置的SqlSessionFactory: <豆ID = “SqlSessionFactory中” 类= “org.mybatis.spring.SqlSessionFactoryBean”> <属性名= “数据源” REF = “数据源”/> <属性名=“typeAliasesPackage “value =”com.llth.paymentgateway.domain“/> 是否可以使用另一个配置的SqlSessionFactoryBean使用另一个数据源? – Tural 2013-02-21 12:31:26

+0

假设我按照您描述的方式配置了dataSources。如何强制映射器中定义的查询使用它们中的任何一个? – Tural 2013-02-21 16:55:25

+0

鉴于您已经正确配置了MyBatis配置,正如[documentation](http://www.mybatis.org/spring/sqlsession.html)中所述,您可以创建sqlSession bean并将其注入到DAO对象中。 – 2013-02-21 21:14:07

0

如果您正在寻找支持不同类型的数据库,我的答案只是为此。
从Mybatis 3开始,它内部支持多数据。有关详细配置,请参阅官方文档at here

以下是如何与Spring

<bean id="vendorProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="properties"> 
     <props> 
      <prop key="SQL Server">sqlserver</prop> 
      <prop key="DB2">db2</prop> 
      <prop key="Oracle">oracle</prop> 
      <prop key="MySQL">mysql</prop> 
     </props> 
    </property> 
</bean> 
<bean id="databaseIdProvider" class="org.apache.ibatis.mapping.VendorDatabaseIdProvider"> 
    <property name="properties" ref="vendorProperties"/> 
</bean> 
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="databaseIdProvider" ref="databaseIdProvider" /> 
</bean>