Spring boot JdbcTemplate Multi-data source configuration and usage

Source: Internet
Author: User
Tags assert

A single data source was used in the previous introduction to using JdbcTemplate and SPRING-DATA-JPA. In the case of a single data source, the Spring boot configuration is very simple, just application.properties configure the connection parameters in the file. But often as the business grows, we usually split the database or introduce other databases, so we need to configure multiple data sources, based on the previous jdbctemplate and SPRING-DATA-JPA examples to describe how two multiple data sources are configured.

Multi-Data Source configuration

Create a spring configuration class that defines the different configurations that are used by the two datasource to read application.properties . In the following example, the primary data source is configured as the spring.datasource.primary beginning of the configuration, and the second data source is configured to spring.datasource.secondary start with the configuration.

Package Com.wls.diypro.util.datasource;import Org.springframework.beans.factory.annotation.qualifier;import Org.springframework.boot.autoconfigure.jdbc.datasourcebuilder;import Org.springframework.boot.context.properties.configurationproperties;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; @Configurationpublic class Datasourceconfig {@Bean (name = "Primarydatasource") @Qualifier ("pri Marydatasource ") @ConfigurationProperties (prefix=" spring.datasource.primary ") Public datasource Primarydatasource (    {return datasourcebuilder.create (). build (); } @Bean (name = "Secondarydatasource") @Qualifier ("Secondarydatasource") @Primary @ConfigurationProperties (pref ix= "Spring.datasource.secondary") public datasource Secondarydatasource () {return datasourcebuilder.cReate (). build (); } @Bean (name = "Primaryjdbctemplate") public JdbcTemplate primaryjdbctemplate (@Qualifier ("Primarydatasou    Rce ") DataSource DataSource) {return new JdbcTemplate (DataSource); } @Bean (name = "Secondaryjdbctemplate") public JdbcTemplate secondaryjdbctemplate (@Qualifier ("Secondaryd    Atasource ") DataSource DataSource) {return new JdbcTemplate (DataSource); }}

  

  

JdbcTemplate support corresponds to the application-dev.yml following configuration:

Spring:  DataSource:    primary:      driver-class-name:com.mysql.jdbc.driver  #    url:jdbc:mysql:// 192.168.159.128:3306/mydb      url:jdbc:mysql://192.168.11.131:3306/mydb      username:wls      Password: wls141215!    Secondary:      driver-class-name:com.mysql.jdbc.driver  #    Url:jdbc:mysql://192.168.159.128:3306/mydb      url:jdbc:mysql://192.168.11.131:3306/shopmall      username:wls      password:wls141215!

Support for JdbcTemplate is relatively simple, only need to inject the corresponding datasource, the following example, in the creation of JdbcTemplate when the name of primaryDataSource secondaryDataSource the data source to be injected to distinguish between different jdbctemplate.

@Autowired    @Qualifier ("primaryjdbctemplate")    protected jdbctemplate primaryjdbctemplate;    @Autowired    @Qualifier ("secondaryjdbctemplate")    protected JdbcTemplate secondaryjdbctemplate;

  

Package Com.wls.diypro.test.jdbctemplatetest;import Com.wls.diypro.model.orderinfo;import Com.wls.diypro.service.iorderinfoservice;import Junit.framework.assert;import Org.junit.Before;import Org.junit.test;import Org.junit.runner.runwith;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.beans.factory.annotation.qualifier;import Org.springframework.boot.test.context.springboottest;import Org.springframework.jdbc.core.jdbctemplate;import Org.springframework.test.context.junit4.springjunit4classrunner;import java.util.Date; @RunWith ( Springjunit4classrunner.class) @SpringBootTestpublic class Jdbctemplatetest {@Autowired @Qualifier ("Primaryjdbctemp    Late ") protected jdbctemplate primaryjdbctemplate;    @Autowired @Qualifier ("secondaryjdbctemplate") protected jdbctemplate secondaryjdbctemplate;    @Autowired private Iorderinfoservice Iorderinfoservice; @Test public void AddOrder () throws Exception {OrderInfo OrderInfo = new OrderInfo ();        Orderinfo.setaddressdetail ("Guangping Street");        Orderinfo.setarea ("Daxing District");        Orderinfo.setcity ("Beijing");        Orderinfo.setordernumber ("10000001");        Orderinfo.setorderstatus ("2");        Orderinfo.setordertime (New Date ());        Orderinfo.setprovince ("Beijing");        Orderinfo.setreceiver ("Miss Wang");        Orderinfo.setstreet ("ces");    Iorderinfoservice.addorder (OrderInfo);        } @Before public void SetUp () {primaryjdbctemplate.update ("DELETE from Order_info");    Secondaryjdbctemplate.update ("DELETE from Order_info"); } @Test public void Test () throws Exception {//Insert two data into the first data source primaryjdbctemplate.update ("Insert int        o Order_info (order_flag,order_number,order_status,street) VALUES (?,?,?,?) "," Test "," 10001 "," S01 "," Guangping Street "); Primaryjdbctemplate.update ("INSERT into Order_info (Order_flag,order_number,order_status,street) VALUES (?,?,?,?)",        "Test", "10001", "S01", "Guangping Street"); Insert a piece of data into the second data source, if the first number is insertedSource, the primary key violation error secondaryjdbctemplate.update ("INSERT into Order_info (order_flag,order_number,order_status,street) Valu        ES (?,?,?,?) "," Test "," 10003 "," S02 "," Guangping Street "); Check to see if there are two data in the first data source, verify that the insertion was successful assert.assertequals ("2", Primaryjdbctemplate.queryforobject ("SELECT count (1) from Ord        Er_info ", String.class)); Check to see if there are two data in the first data source, verify that the insertion was successful assert.assertequals ("1", Secondaryjdbctemplate.queryforobject ("SELECT count (1) from O    Rder_info ", String.class)); }}

  

Complete Example: Guithub The next test case demonstrates how to use these two jdbctemplate for different data sources.

Spring boot JdbcTemplate Multi-data source configuration and usage

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.