springboot2连接多数据库mysql+oracle
使用下面两种类型数据库:
1. mysql的版本5.5.28 (select @@version), user是其中的一张表格
2. oracle的版本11.2.0.1.0(select * from v$version), userinfo是其中的一张表格
使用IntelliJ IDEAL建立springboot项目, springboot的版本是 2.2.6.RELEASE.
pom.xml文件内容如下:
要加入以下内容, 这样才能连接Mysql和Oracle数据库
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency>
application.yml内容如下:
server:
port: 8082
spring:
profiles:
active: dev
application-dev.yml内容如下:
spring: datasource: primary: #mysql database config driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/testMysql?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: mysqlUsername password: mysqlPassword secondary: #oracle database config driverClassName: oracle.jdbc.OracleDriver url: jdbc:oracle:thin:@localhost:1521:testOracle username: oracleUsername password: oraclePassword
mybatis:
mapper-locations: classpath:mapper/mysql/*.xml, classpath:mapper/oracle/*.xml
config-location: classpath:config/mybatis/mybatis_config.xml
type-aliases-package: com.test.demo.pojo.mysql, com.test.demo.pojo.oracle
DataSourceConfig.java 这是数据库配置的共同文件,其实就是抽取共性的操作而已.
package com.test.demo.config; import com.test.demo.utils.CommonVariable; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; public class DataSourceConfig { private static final Logger LOG = LoggerFactory.getLogger(DataSourceConfig.class);
/*
* 这里主要加载对应数据库的mapper.xml和对应的pojo文件.
* 因为要加载两种数据库, 所以配置只能通过java代码来动态配置.
*/ public SqlSessionFactory sqlSessionFactory(DataSource dataSource, String dataBaseType) throws Exception { LOG.info("dataBaseType:" + dataBaseType); SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factoryBean.setDataSource(dataSource); if (CommonVariable.MYSQL.equalsIgnoreCase(dataBaseType)) { factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/mysql/*.xml")); //这里加载Mysql下面的xml文件 factoryBean.setTypeAliasesPackage("com.test.demo.pojo.mysql"); //这里加载Mysql下面的对应的pojo } else if (CommonVariable.ORACLE.equalsIgnoreCase(dataBaseType)) { factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/oracle/*.xml")); //这里加载Oracle下面的xml factoryBean.setTypeAliasesPackage("com.xum.demo.pojo.oracle"); //这里加载Oracle下面对应的pojo } factoryBean.setConfigLocation(resolver.getResource("classpath:config/mybatis/mybatis_config.xml")); //这里加载共同的config return factoryBean.getObject(); } }
MySqlDataSourceConfig.java, 这是mysql的配置, 加@Primary是首先的配置数据库
package com.test.demo.config; import com.alibaba.druid.pool.DruidDataSource; import com.test.demo.utils.CommonVariable; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.test.demo.dao.mysql", sqlSessionFactoryRef = "mysqlSqlSessionFactory") public class MySqlDataSourceConfig extends DataSourceConfig { private static final Logger LOG = LoggerFactory.getLogger(MySqlDataSourceConfig.class); @Value("${spring.datasource.primary.url}") private String url; @Value("${spring.datasource.primary.driverClassName}") private String driverClassName; @Value("${spring.datasource.primary.username}") private String username; @Value("${spring.datasource.primary.password}") private String password; @Primary @Bean(name = "mysqlDataSource") public DataSource mysqlDataSource() { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driverClassName); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } @Primary @Bean(name = "mysqlTransactionManager") public DataSourceTransactionManager mysqlTransactionManager( @Qualifier(value = "mysqlDataSource") DataSource dataSource) { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource); return dataSourceTransactionManager; } @Primary @Bean(name = "mysqlSqlSessionFactory") public SqlSessionFactory sqlSessionFactory( @Qualifier(value = "mysqlDataSource") DataSource dataSource) throws Exception { SqlSessionFactory factoryBean = super.sqlSessionFactory(dataSource, CommonVariable.MYSQL); return factoryBean; } @Primary @Bean(name = "mysqlSqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier(value = "mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
OracleDataSourceConfig.java, 这是oracle的配置
package com.test.demo.config; import com.alibaba.druid.pool.DruidDataSource; import com.test.demo.utils.CommonVariable; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.xum.demo.dao.oracle", sqlSessionFactoryRef = "oracleSqlSessionFactory") public class OracleDataSourceConfig extends DataSourceConfig { private static final Logger LOG = LoggerFactory.getLogger(OracleDataSourceConfig.class); @Value("${spring.datasource.secondary.url}") private String url; @Value("${spring.datasource.secondary.driverClassName}") private String driverClassName; @Value("${spring.datasource.secondary.username}") private String username; @Value("${spring.datasource.secondary.password}") private String password; @Bean(name = "oracleDataSource") public DataSource oracleDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } @Bean(name = "oracleTransactionManager") public DataSourceTransactionManager oracleTransactionManager( @Qualifier(value = "oracleDataSource") DataSource dataSource) { DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); return manager; } @Bean(name = "oracleSqlSessionFactory") public SqlSessionFactory sqlSessionFactory( @Qualifier(value = "oracleDataSource") DataSource dataSource) throws Exception { SqlSessionFactory factoryBean = super.sqlSessionFactory(dataSource, CommonVariable.ORACLE); return factoryBean; } @Bean(name = "oracleSqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier(value = "oracleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
CommonVariable.java内容, 这里只是常量文件class
package com.test.demo.utils; public class CommonVariable { public final static String MYSQL = "mysql"; public final static String ORACLE = "oracle"; }
随便写一个controller来测试:
@Controller @RequestMapping("/index") public class UserController { private static final Logger LOG = LoggerFactory.getLogger(UserController.class); private static final int successStatus = 200; private static final int failedStatus = 100; @Autowired private UserService userService; @Autowired private UserinfoService userinfoService; @RequestMapping(value="/updateUserByMysql", method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseBody public String updateUser(@RequestBody(required=true) User user) { String status = "{\"status\" : \"" + successStatus + "\"}"; int affectRow = this.userService.updateByPrimaryKeySelective(user); if (-1 == affectRow) { status = "{\"status\" : \"" + failedStatus + "\"}"; } return status; } @RequestMapping(value="/updateUserinfoByOracle", method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseBody public String updateUserinfo(@RequestBody(required=true) Userinfo userinfo) { String status = "{\"status\" : \"" + successStatus + "\"}"; int affectRow = this.userinfoService.updateByPrimaryKeySelective(userinfo); if (-1 == affectRow) { status = "{\"status\" : \"" + failedStatus + "\"}"; } return status; } }
当执行http://localhost:8082/index/updateUserByMysql 和http://localhost:8082/index/updateUserinfoByOracle,
都可以成功.
个人感觉, SpringBoot在连接数据库的时候,是先根据Primary的这个注解来先执行的,
如果没有合适的话, 它会使用secondary类型连接数据库的.
努力做一个伪程序员, 不管道路有多么的艰苦......
posted on 2020-04-18 20:38 努力做一个伪程序员 阅读(1811) 评论(0) 编辑 收藏 举报