application.yml配置
spring:
datasource:
oracle:
driver-class-name: oracle.jdbc.OracleDriver
jdbc-url: jdbc:oracle:thin:@210.12.140.221:30002:jzd
password: jzd_za_dubo_2020
username: za_dubo
mysql:
username: root
password: 123456
jdbc-url: jdbc:mysql://localhost:3306/worklog?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.jdbc.Driver
启动程序DemoApplication
闯将datasource对象,并注入相应的数据库配置,再创建jdbcTemplate对象,并注入相应的datasource对象即可
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean("datasourceOracle")
@ConfigurationProperties("spring.datasource.oracle")
public HikariDataSource datasourceOracle() {
return new HikariDataSource();
}
@Bean("jdbcTemplateOracle")
public JdbcTemplate jdbcTemplateOracle() {
return new JdbcTemplate(datasourceOracle());
}
@Bean("datasourceMysql")
@ConfigurationProperties("spring.datasource.mysql")
public HikariDataSource datasourceMysql() {
return new HikariDataSource();
}
@Bean("jdbcTemplateMysql")
public JdbcTemplate jdbcTemplateMysql() {
return new JdbcTemplate(datasourceMysql());
}
}
使用方式
@SpringBootTest
class DemoApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplateOracle;
@Autowired
private JdbcTemplate jdbcTemplateMysql;
@Test
void testOracle() {
String sql = "select * from item";
List<Map<String, Object>> maps = jdbcTemplateOracle.queryForList(sql);
for (Map<String, Object> map : maps) {
System.out.println(map.get("name"));
}
}
@Test
void testMysql() {
String sql = "select * from item";
List<Map<String, Object>> maps = jdbcTemplateMysql.queryForList(sql);
for (Map<String, Object> map : maps) {
System.out.println(map.get("name"));
}
}
}