Spring-boot JDBC with multiple DataSources sample

Source: Internet
Author: User
Tags postgresql

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 is the less trivial configuration and when do you have several different databases?

I found the multiple datasources for spring-boot-based application.

In the sample below I has a special (db-related) configurations, one properties file with connections ' parameters and T Wo repositories.

Each @Repository connects with appropriate database through separate DataSource.
Application.properties
Spring.ds_items.driverClassName=org.postgresql.driver spring.ds_items.url=< span class= "s2" >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
PackageSbImportOrg.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;ImportOrg.springframework.boot.context.properties.ConfigurationProperties;ImportOrg.springframework.context.annotation.Bean;ImportOrg.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") C18>public jdbctemplate jdbctemplate (DataSource dsitems) { return new JdbcTemplate (Dsitems);}}  



Databaseusersconfig.java
PackageSbImportOrg.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;ImportOrg.springframework.boot.context.properties.ConfigurationProperties;ImportOrg.springframework.context.annotation.Bean;ImportOrg.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") C18>public jdbctemplate jdbctemplate (DataSource dsusers) { return new JdbcTemplate (dsusers);}}  



Itemrepository.java
PackageSbImportOrg.slf4j.Logger;ImportOrg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Qualifier;ImportOrg.springframework.jdbc.core.JdbcTemplate;ImportOrg.springframework.jdbc.core.RowMapper;ImportOrg.springframework.stereotype.Repository;ImportJava.sql.ResultSet;ImportJava.sql.SQLException; @Repositorypublic classitemrepository {Protected finalLogger log = Loggerfactory.getlogger (GetClass ()); @Autowired @Qualifier ("Jdbcitems")ProtectedJdbcTemplate JDBC;PublicItem GetItem (long id) {return jdbc.queryforobject ( "SELECT * from Sb_item WHERE id=?" private static final rowmapper<item> itemmapper = new rowmapper<item> () {public item Maprow (ResultSet RS, int rownum) throws sqlexception {Item item = Span class= "S0" >new item (Rs.getlong ( "id"  "title"  "id" return item;}; }  



Userrepository.java
PackageSbImportOrg.slf4j.Logger;ImportOrg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Qualifier;ImportOrg.springframework.jdbc.core.JdbcTemplate;ImportOrg.springframework.jdbc.core.RowMapper;ImportOrg.springframework.stereotype.Repository;ImportJava.sql.ResultSet;ImportJava.sql.SQLException; @Repositorypublic classuserrepository {Protected finalLogger log = Loggerfactory.getlogger (GetClass ()); @Autowired @Qualifier ("Jdbcusers")ProtectedJdbcTemplate JDBC;PublicUser GetUser (long id) {return jdbc.queryforobject ( "SELECT * from Sb_user WHERE id=?" private static final rowmapper<user> usermapper = new rowmapper<user> () {public user Maprow (ResultSet RS, int rownum) throws sqlexception {User user = Span class= "S0" >new user (Rs.getlong ( "id"  "name"  "alias" return user;}; }  



Controller.java
PackageSbImportOrg.slf4j.Logger;ImportOrg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.bind.annotation.RestController; @RestControllerpublic classController {Protected finalLogger log = Loggerfactory.getlogger (GetClass ()); @AutowiredPrivateUserrepository users; @AutowiredPrivateItemrepository items; @RequestMapping ("Test")PublicString Test () {Log.info ( "Test" ); return  "OK"  "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
PackageSbImportOrg.springframework.boot.SpringApplication;ImportOrg.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 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.