Spring boot multi-data source configuration and usage

Source: Internet
Author: User
Tags assert

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 two DataSource

@Configuration Public classdatasourceconfig {@Bean (name="Primarydatasource") @Qualifier ("Primarydatasource") @ConfigurationProperties (prefix="spring.datasource.primary")     PublicDataSource Primarydatasource () {returndatasourcebuilder.create (). build (); } @Bean (Name="Secondarydatasource") @Qualifier ("Secondarydatasource") @Primary @ConfigurationProperties (prefix="spring.datasource.secondary")     PublicDataSource Secondarydatasource () {returndatasourcebuilder.create (). build (); }}

The corresponding application.properties configuration is as follows:

Spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1 Spring.datasource.primary.username=Rootspring.datasource.primary.password=  Rootspring.datasource.primary.driver-class-name=  Com.mysql.jdbc.Driverspring.datasource.secondary.url=jdbc:mysql://localhost:3306/test2 Spring.datasource.secondary.username=Rootspring.datasource.secondary.password=  Rootspring.datasource.secondary.driver-class-name=com.mysql.jdbc.driver
JdbcTemplate Support

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.

@Bean (name ="primaryjdbctemplate") PublicJdbcTemplate primaryjdbctemplate (@Qualifier ("Primarydatasource") DataSource DataSource) {return NewJdbcTemplate (DataSource);} @Bean (Name="secondaryjdbctemplate") PublicJdbcTemplate secondaryjdbctemplate (@Qualifier ("Secondarydatasource") DataSource DataSource) {return NewJdbcTemplate (DataSource);}

Next, test cases demonstrate how to use these two jdbctemplate for different data sources.

@RunWith (Springjunit4classrunner.class) @SpringApplicationConfiguration (application.class) Public classapplicationtests {@Autowired @Qualifier ("primaryjdbctemplate")    protectedJdbcTemplate jdbcTemplate1; @Autowired @Qualifier ("secondaryjdbctemplate")    protectedJdbcTemplate JdbcTemplate2; @Before Public voidsetUp () {jdbctemplate1.update ("DELETE from USER"); Jdbctemplate2.update ("DELETE from USER"); } @Test Public voidtest () throws Exception {//insert two data into the first data sourceJdbctemplate1.update ("INSERT INTO User (Id,name,age) VALUES (?,?,?)",1,"AAA", -); Jdbctemplate1.update ("INSERT INTO User (Id,name,age) VALUES (?,?,?)",2,"BBB", -); //insert a data into the second data source, if the first data source is inserted, the primary key conflict errorJdbctemplate2.update ("INSERT INTO User (Id,name,age) VALUES (?,?,?)",1,"AAA", -); //Check to see if there are two data in the first data source to verify that the insertion was successfulAssert.assertequals ("2", Jdbctemplate1.queryforobject ("Select COUNT (1) from user", String.class)); //Check to see if there are two data in the first data source to verify that the insertion was successfulAssert.assertequals ("1", Jdbctemplate2.queryforobject ("Select COUNT (1) from user", String.class)); }}
SPRING-DATA-JPA Support

Add a new JPA configuration to the first data source, noting where two notes are, specifying the Entity entity and definition location for the data source Repository , and @Primary distinguishing between the primary data source.

@Configuration @enabletransactionmanagement@enablejparepositories (entitymanagerfactoryref="entitymanagerfactoryprimary", Transactionmanagerref="transactionmanagerprimary", Basepackages= {"COM.DIDISPACE.DOMAIN.P"})//Set Repository location Public classprimaryconfig {@Autowired @Qualifier ("Primarydatasource")    PrivateDataSource Primarydatasource; @Primary @Bean (Name="entitymanagerprimary")     PublicEntitymanager Entitymanager (Entitymanagerfactorybuilder builder) {returnentitymanagerfactoryprimary (builder). GetObject (). Createentitymanager (); } @Primary @Bean (name="entitymanagerfactoryprimary")     PublicLocalcontainerentitymanagerfactorybean entitymanagerfactoryprimary (Entitymanagerfactorybuilder builder) {returnBuilder. DataSource (Primarydatasource). Properties (Getvendorproperties (PRIMARYDATASOURC e). Packages ("COM.DIDISPACE.DOMAIN.P")//set where entity classes are located. Persistenceunit ("Primarypersistenceunit"). build (); } @AutowiredPrivatejpaproperties jpaproperties; PrivateMap<string, string>getvendorproperties (DataSource DataSource) {returnjpaproperties.gethibernateproperties (DataSource); } @Primary @Bean (name="transactionmanagerprimary")     PublicPlatformtransactionmanager transactionmanagerprimary (Entitymanagerfactorybuilder builder) {return NewJpatransactionmanager (Entitymanagerfactoryprimary (builder). GetObject ()); }}

A new JPA configuration for the second data source, similar to the first data source, is as follows:

@Configuration @enabletransactionmanagement@enablejparepositories (entitymanagerfactoryref="entitymanagerfactorysecondary", Transactionmanagerref="transactionmanagersecondary", Basepackages= {"com.didispace.domain.s"})//Set Repository location Public classsecondaryconfig {@Autowired @Qualifier ("Secondarydatasource")    PrivateDataSource Secondarydatasource; @Bean (Name="entitymanagersecondary")     PublicEntitymanager Entitymanager (Entitymanagerfactorybuilder builder) {returnentitymanagerfactorysecondary (builder). GetObject (). Createentitymanager (); } @Bean (Name="entitymanagerfactorysecondary")     PublicLocalcontainerentitymanagerfactorybean entitymanagerfactorysecondary (Entitymanagerfactorybuilder builder) { /c8>returnBuilder. DataSource (Secondarydatasource). Properties (Getvendorproperties (Secondarydatas Ource)). Packages ("com.didispace.domain.s")//set where entity classes are located. Persistenceunit ("Secondarypersistenceunit"). build (); } @AutowiredPrivatejpaproperties jpaproperties; PrivateMap<string, string>getvendorproperties (DataSource DataSource) {returnjpaproperties.gethibernateproperties (DataSource); } @Bean (Name="transactionmanagersecondary") Platformtransactionmanager transactionmanagersecondary (Entitymanagerfactorybuilder builder) {return NewJpatransactionmanager (Entitymanagerfactorysecondary (builder). GetObject ()); }}

After the above configuration has been completed, the entity and data access objects of the primary data source are located: com.didispace.domain.p , the entity and data access interfaces of the secondary data source are located at: com.didispace.domain.s .

Spring boot 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.