Springboot integrating multiple data sources and things

Source: Internet
Author: User

There are two ways: one is the way of subcontracting, the other is annotated (@DataSource (ref= "")).

Subcontracting method: The project structure is as follows:

                          

Divided into com.itmayiedu.test01,com.itmayiedu.test02 Two packets inside is the DAO and service layer, data manipulation.

Com.itmayiedu.datasource inside the data source, database things. Two configurations are the same.

Two data sources, you need to add @primary annotations in one, as the main data source, or the database can not find the main error; After Springboot 2.0 version, you do not need to add @primary annotations

 PackageCom.itmayiedu.datasource;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.mybatis.spring.SqlSessionFactoryBean;Importorg.mybatis.spring.SqlSessionTemplate;ImportOrg.mybatis.spring.annotation.MapperScan;ImportOrg.springframework.beans.factory.annotation.Qualifier;ImportOrg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;Importorg.springframework.boot.context.properties.ConfigurationProperties;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;Importorg.springframework.context.annotation.Primary;ImportOrg.springframework.jdbc.datasource.DataSourceTransactionManager;ImportJavax.sql.DataSource;//DataSource01@Configuration//Register in the Springboot container@MapperScan (basepackages = "com.itmayiedu.test01", Sqlsessionfactoryref = "Test1sqlsessionfactory") Public classDatasource1config {/*** * @methodDesc: Function Description: (Configure TEST1 database) *@author: Yu Shengjun *@param: @return* @createTime: September 17, 2017 pm 3:16:44 * @returnType:@returnDataSource * @copyright: Shanghai Every Special Education Technology Co., Ltd. * @QQ: 644064779*/@Bean (Name= "Test1datasource") @ConfigurationProperties (prefix= "Spring.datasource.test1") @Primary  PublicDataSource Testdatasource () {returndatasourcebuilder.create (). build (); }    /*** * @methodDesc: Function Description: (Test1 SQL Session factory) *@author: Yu Shengjun *@param: @param* DataSource *@param: @return     * @param: @throws* Exception * @createTime: September 17, 2017 pm 3:17:08 * @returnType:@paramDataSource * @returnType:@return* @returnType:@throwsException sqlsessionfactory * @copyright: Shanghai Every Special Education Technology Co., Ltd. * @QQ: 644064779*/@Bean (Name= "Test1sqlsessionfactory") @Primary  PublicSqlsessionfactory testsqlsessionfactory (@Qualifier ("Test1datasource") DataSource DataSource)throwsException {Sqlsessionfactorybean bean=NewSqlsessionfactorybean ();        Bean.setdatasource (DataSource); //Bean.setmapperlocations (//New//pathmatchingresourcepatternresolver (). Getresources ("Classpath:mybatis/mapper/test1/*.xml"));        returnBean.getobject (); }    /*** * @methodDesc: Function Description: (test1 things Management) *@author: Yu Shengjun *@param: @param* DataSource *@param: @return     * @param: @throws* Exception * @createTime: September 17, 2017 pm 3:17:08 * @returnType:@paramDataSource * @returnType:@return* @returnType:@throwsException sqlsessionfactory * @copyright: Shanghai Every Special Education Technology Co., Ltd. * @QQ: 644064779*/@Bean (Name= "Test1transactionmanager") @Primary  PublicDatasourcetransactionmanager Testtransactionmanager (@Qualifier ("Test1datasource") DataSource DataSource) {return NewDatasourcetransactionmanager (DataSource); } @Bean (Name= "Test1sqlsessiontemplate") @Primary  Publicsqlsessiontemplate testsqlsessiontemplate (@Qualifier ("Test1sqlsessionfactory") sqlsessionfactory sqlsessionfactory)throwsException {return Newsqlsessiontemplate (sqlsessionfactory); }}

Application.properties:

== jdbc:mysql://localhost:3306/chapter3?useunicode=true&characterencoding=utf-8 Spring.datasource.test1.username == = = Jdbc:mysql://localhost:3306/ Chapter13?useunicode=true&characterencoding=utf-8spring.datasource.test2.username == Zhaocheng

TestController:

Add @Transactional (TransactionManager = "Test1transactionmanager") to Add and differentiate things.

 PackageCom.itmayiedu.controller;Importcom.itmayiedu.test01.service.UserServiceTest01;Importcom.itmayiedu.test02.service.UserServiceTest02;Importlombok.extern.slf4j.Slf4j;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.transaction.annotation.Transactional;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController, @RestController @slf4j Public classTestController {@AutowiredPrivateUserServiceTest01 userServiceTest01; @AutowiredPrivateUserServiceTest02 userServiceTest02; @RequestMapping ("/teststring")     PublicString teststring () {Log.info ("TestString"); return"Springboot01 Test"; } @RequestMapping ("/insert") @Transactional (TransactionManager= "Test1transactionmanager")     PublicInteger insertrole (String role_name,string Note) {Log.info ("111111"); Integer a=Userservicetest01.insertrole (role_name, note); intb = 100/integer.valueof (note); returnA; } @RequestMapping ("/update") @Transactional (TransactionManager= "Test2transactionmanager")     PublicInteger updaterole (String role_name,string Note) {Log.info ("222222"); Integer a=Userservicetest02.insertrole (role_name, note); intb = 100/integer.valueof (note); returnA; }}

Startup class Application:

 Packagecom.itmayiedu;ImportOrg.mybatis.spring.annotation.MapperScan;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;ImportOrg.springframework.context.annotation.ComponentScan, @SpringBootApplication @componentscan@mapperscan ("Com.itmayiedu.*.mapper") Public classApplication { Public Static voidMain (string[] args) {springapplication.run (application.class, args); }}

Inside this is the addition of the @MapperScan ("Com.itmayiedu.*.mapper") at boot is a sweep package, or you can add @mapper annotations at each DAO layer.

USERMAPPERTEST01:

 PackageCom.itmayiedu.test01.mapper;ImportCom.itmayiedu.entity.User;ImportOrg.apache.ibatis.annotations.Insert;ImportOrg.apache.ibatis.annotations.Param;ImportOrg.apache.ibatis.annotations.Select;Importorg.springframework.stereotype.Repository; @Repository Public InterfaceUserMapperTest01 {@Select ("SELECT * from t_role WHERE role_name = #{role_name}") User findbyname (@Param ("Role_name") String role_name); @Insert ("INSERT into T_role (Role_name, NOTE) VALUES (#{role_name}, #{note})")    intInsert (@Param ("Role_name") String Role_name, @Param ("note") String note);}

USERSERVICETEST01:

 PackageCom.itmayiedu.test01.service;Importcom.itmayiedu.test01.mapper.UserMapperTest01;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service; @Service Public classUserServiceTest01 {@AutowiredPrivateUserMapperTest01 userMapperTest01;  PublicInteger insertrole (String role_name,string Note) {returnUsermappertest01.insert (role_name, note); }}

Springboot integrating multiple data sources and things

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.