Oracle与mysql双数据源配置_Spring+Mybatis多数据源配置(一)——MySQL与Oracle通过配置切换...

在小型项目中,一般配置一个数据库,也就是一个mybatis数据源,但是有时候需要同时支持两种数据库,比如mysql和oracle. 最笨的方法就是配置两个spring配置文件,然后根据不同的部署,采用不同的配置文件,其实这两个配置文件可以合成一个配置文件,通过java的properties文件进行配置。

首先说明下配置单个数据库,也就是单个数据源的配置。

首先看一下spring的配置文件applicationContext.xml(这里采用的是spring+mybatis,所以有关数据库的及mybatis的配置都在这里):

http://www.springframework.org/schema/beans

classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd

http://www.springframework.org/schema/aop

classpath:/org/springframework/aop/config/spring-aop-3.0.xsd

http://www.springframework.org/schema/context

classpath:/org/springframework/context/config/spring-context-3.0.xsd

http://www.springframework.org/schema/tx

classpath:/org/springframework/transaction/config/spring-tx-3.0.xsd">

classpath:com/shr/dao/resources/mappers/*_mapper.xml

properties配置文件内容为:

#mysql configuration

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://10.10.193.111:3306/sp5000?useUnicode=true&characterEncoding=UTF-8

username=shr

password=shr

通过properties配置文件可以看到我们所配的数据库是mysql.

在applicationContext.xml文件中,我们只配置了一个数据源,就是“dataSource”,存放mybatis配置文件的地方为:

classpath:com/shr/dao/resources/mappers/*_mapper.xml

接下去,进行配置双数据源,通过properties配置文件进行切换,我们首先看下config.properties文件的内容:

# oracle configuration

ora_driver=oracle.jdbc.driver.OracleDriver

ora_url=jdbc:oracle:thin:@10.10.195.185:1521:sp5000

ora_username=shr

ora_password=shr

#mysql configuration

mysql_driver=com.mysql.jdbc.Driver

mysql_url=jdbc:mysql://10.10.193.111:3306/sp5000?useUnicode=true&characterEncoding=UTF-8

mysql_username=shr

mysql_password=shr

dataSource=mysql

可以看到分别对mysql以及oracle的数据库进行了配置,并且标注了“dataSource”这个字段,这个就是进行数据源切换的配置。

接着来看一下修改后的applicationContext.xml文件内容:

http://www.springframework.org/schema/beans

classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd

http://www.springframework.org/schema/aop

classpath:/org/springframework/aop/config/spring-aop-3.0.xsd

http://www.springframework.org/schema/context

classpath:/org/springframework/context/config/spring-context-3.0.xsd

http://www.springframework.org/schema/tx

classpath:/org/springframework/transaction/config/spring-tx-3.0.xsd">

classpath:com/shr/dao/resources/${dataSource}mappers/*_mapper.xml

可以看到这里配置了两个数据源,分别为“mysql”和“oracle”,这个值对应config.properties配置文件中的dataSource字段。通过${dataSource}可以引用不同的数据源。

由于mysql和oracle之间sql语法有一定的差异性,所以这里需要采用两种不同的mybatis配置文件:

classpath:com/shr/dao/resources/${dataSource}mappers/*_mapper.xml

根据这个配置可以关联两种不同的mybatis配置文件,譬如mysql对应classpath:com/shr/dao/resources/mysqlmappers/*_mapper.xml。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值