Spring-boot JDBC with multiple DataSources sample
Spring-Boot's auto-configurer seems good for simple applications. For example it automatically creates DataSource and JdbcTemplate, when you need to connect to the database. But what about less trivial configuration, when you have several different databases?
I found the way to have multiple DataSources for Spring-Boot-based application. In the sample below I have two special (db-related) Configurations, one properties file with connections' parameters and two Repositories. Each @Repository connects with appropriate database through separate DataSource. |
application.properties |
spring.ds_items.driverClassName=org.postgresql.Driver
spring.ds_items.url=jdbc:postgresql://srv0/test
spring.ds_items.username=test0
spring.ds_items.password=test0 spring.ds_users.driverClassName=org.postgresql.Driver
spring.ds_users.url=jdbc:postgresql://srv1/test
spring.ds_users.username=test1
spring.ds_users.password=test1
DatabaseItemsConfig.java |
package sb; import org.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration
@ConfigurationProperties(name = "spring.ds_items")
public class DatabaseItemsConfig extends TomcatDataSourceConfiguration { @Bean(name = "dsItems")
public DataSource dataSource() {
return super.dataSource();
} @Bean(name = "jdbcItems")
public JdbcTemplate jdbcTemplate(DataSource dsItems) {
return new JdbcTemplate(dsItems);
}
}
DatabaseUsersConfig.java |
package sb; import org.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration
@ConfigurationProperties(name = "spring.ds_users")
public class DatabaseUsersConfig extends TomcatDataSourceConfiguration { @Bean(name = "dsUsers")
public DataSource dataSource() {
return super.dataSource();
} @Bean(name = "jdbcUsers")
public JdbcTemplate jdbcTemplate(DataSource dsUsers) {
return new JdbcTemplate(dsUsers);
} }
ItemRepository.java |
package sb; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository; import java.sql.ResultSet;
import java.sql.SQLException; @Repository
public class ItemRepository {
protected final Logger log = LoggerFactory.getLogger(getClass()); @Autowired
@Qualifier("jdbcItems")
protected JdbcTemplate jdbc; public Item getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
} private static final RowMapper<Item> itemMapper = new RowMapper<Item>() {
public Item mapRow(ResultSet rs, int rowNum) throws SQLException {
Item item = new Item(rs.getLong("id"), rs.getString("title"));
item.price = rs.getDouble("id");
return item;
}
};
}
UserRepository.java |
package sb; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository; import java.sql.ResultSet;
import java.sql.SQLException; @Repository
public class UserRepository {
protected final Logger log = LoggerFactory.getLogger(getClass()); @Autowired
@Qualifier("jdbcUsers")
protected JdbcTemplate jdbc; public User getUser(long id) {
return jdbc.queryForObject("SELECT * FROM sb_user WHERE id=?", userMapper, id);
} private static final RowMapper<User> userMapper = new RowMapper<User>() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User(rs.getLong("id"), rs.getString("name"));
user.alias = rs.getString("alias");
return user;
}
};
}
Controller.java |
package sb; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController
public class Controller {
protected final Logger log = LoggerFactory.getLogger(getClass()); @Autowired
private UserRepository users; @Autowired
private ItemRepository items; @RequestMapping("test")
public String test() {
log.info("Test");
return "OK";
} @RequestMapping("user")
public User getUser(@RequestParam("id") long id) {
log.info("Get user");
return users.getUser(id);
} @RequestMapping("item")
public Item getItem(@RequestParam("id") long id) {
log.info("Get item");
return items.getItem(id);
} }
Application.java |
package sb; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
@Configuration
@ComponentScan(basePackages = "sb")
public class Application { public static void main(String[] args) throws Throwable {
SpringApplication app = new SpringApplication(Application.class);
app.run();
}
}
Spring-boot JDBC with multiple DataSources sample的更多相关文章
- 【Spring-boot多数据库】Spring-boot JDBC with multiple DataSources sample
application.properties spring.ds_items.driverClassName=org.postgresql.Driver spring.ds_items.url=jdb ...
- (转) Spring Boot JDBC 连接数据库
文本将对在Spring Boot构建的Web应用中,基于MYSQL数据库的几种数据库连接方式进行介绍. 包括JDBC.JPA.MyBatis.多数据源和事务. 1 JDBC 连接数据库 1.1 属性配 ...
- Spring Boot JDBC 连接数据库
文本将对在Spring Boot构建的Web应用中,基于MYSQL数据库的几种数据库连接方式进行介绍. 包括JDBC.JPA.MyBatis.多数据源和事务. JDBC 连接数据库 1.属性配置文件( ...
- Spring boot + jdbc学习笔记
pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. ...
- Spring Boot JDBC:加载DataSource过程的源码分析及yml中DataSource的配置
装载至:https://www.cnblogs.com/storml/p/8611388.html Spring Boot实现了自动加载DataSource及相关配置.当然,使用时加上@EnableA ...
- Spring Boot JDBC 使用教程
总是要用到数据库的嘛,曾经我一度以为,写代码,编程就是搞数据库增删改查,甚至你设计一个系统,大部分时候在为如何设计关系型数据库努力,究其原因,是因为关系型数据库是逻辑的主要呈现. 这个系列,主要是对 ...
- Spring Boot: Jdbc javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify
jdbc:mysql://127.0.0.1:3306/xxx?useSSL=false 在后面添加?useSSL=false即可 参考网站
- 10. Spring Boot JDBC 连接数据库
转自:https://blog.csdn.net/catoop/article/details/50507516
- 二、spring Boot构建的Web应用中,基于MySQL数据库的几种数据库连接方式进行介绍
包括JDBC.JPA.MyBatis.多数据源和事务. 一.JDBC 连接数据库 1.属性配置文件(application.properties) spring.datasource.url=jdbc ...
随机推荐
- centos python版本升级到3.x
Linux(CentOS)下将Python的版本升级为3.6.2的方法 1.检查确认系统的相关信息 查看内核版本[root@zstest1 ~]# cat /etc/redhat-release Ce ...
- C++-函数与指针的关系(回调函数)
1.函数类型 C语言中的函数有自己特定的类型 函数的类型由返回值,参数类型和参数个数共同决定 ★ int add(int i, int j)的类型为int(int, int) C语言中通过typede ...
- yingwen
In older people with mild cognitive impairment,having a drink now and then -- up to an average of on ...
- oracle分组并在组内排序
根据c1,c2分组,并且根据c3排序,取第一行select tt.* from (select row_number() over(partition by c1, c2 order by c3 d ...
- IIS的部署
https://blog.csdn.net/miner_k/article/details/69388726 https://blog.csdn.net/miner_k/article/details ...
- python skimage库的安装
skimage库需要依赖 numpy+mkl 和scipy 1.打开运行,输入cmd回车,输入python回车,查看python版本
- C++-POJ1200-Crazy Search[hash]
由于已经给出字符只有NC种,故可以把子串视为一个NC进制的数,以此构造hash函数就可以了 #include <set> #include <map> #include < ...
- php:对象(object)数据类型实例详解
什么是对象? 对象是存储数据和有关如何处理数据的信息的数据类型.是系统中用来描述客观事物的一个实体,它是构成系统的一个基本单位.一个对象由一组属性和对这组属性进行操作的一组服务组成. 语法 在 PHP ...
- 马俊龙ansible教程分享
ansible详细介绍和教程链接:https://www.cnblogs.com/f-ck-need-u/p/7576137.html#ansible
- HTML学习(17)URL
HTML 统一资源定位器(Uniform Resource Locators) URL - 统一资源定位器 Web浏览器通过URL从Web服务器请求页面. scheme://host.domain:p ...