springboot 配置oracle和mysql数据源,使用jdbc连接
1.application.yal文件配置

我使用的是mysql 8.0.18的数据库,目前最新版,注意:加上serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
新的driver-class-name: com.mysql.cj.jdbc.Driver写法
2. pom.xml配置
4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE test test 0.0.1-SNAPSHOT test Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine org.springframework.boot spring-boot-starter-jdbc mysql mysql-connector-java runtime com.oracle ojdbc6 12.2.0.1 org.springframework.boot spring-boot-maven-plugin
3. 在config文件下新建DataSourceConfig类
package test.test.config;import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;import javax.sql.DataSource;@Configuration
public class DataSourceConfig {@Bean(name = "primaryDataSource")@Qualifier("primaryDataSource")@ConfigurationProperties(prefix="spring.datasource.primary")public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "secondaryDataSource")@Qualifier("secondaryDataSource")@Primary@ConfigurationProperties(prefix="spring.datasource.secondary")public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "primaryJdbcTemplate")public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {return new JdbcTemplate(dataSource);}@Bean(name = "secondaryJdbcTemplate")public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {return new JdbcTemplate(dataSource);}}
4.测试
package test.test;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class TestController {@Autowired@Qualifier("primaryJdbcTemplate")protected JdbcTemplate jdbcTemplate1;@Autowired@Qualifier("secondaryJdbcTemplate")protected JdbcTemplate jdbcTemplate2;@RequestMapping("/test")public List getCxzdb(){// String sql = "SELECT * FROM sys_user";String sql = "select azf01,azf03 from t00.azf_file";List list = jdbcTemplate1.queryForList(sql);return list;}@RequestMapping("/getList")public List getList() {String sql = "SELECT * FROM user";List list = jdbcTemplate2.queryForList(sql);return list;}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
