Springboot--springboot+mybatis solution for multiple data sources

Source: Internet
Author: User

Talking about multi-data sources, generally to solve those problems, master-slave mode or business complex need to connect different sub-Libraries to support the business. Our project is the latter model, the Internet to find a lot, mostly based on JPA to do a long data source solution, or is the old spring Multi-data source solution, but also some of the use of AOP dynamic switching, feeling a little complex, in fact, I just want to find a simple majority supported by it, Two hours of tossing and finishing out for your reference.


No more nonsense, just go straight to the code.
Configuration file
POM package is not affixed to the relatively simple dependency on the dependency, mainly the database side of the configuration:

 mybatis.config-locations=classpath:mybatis/mybatis- Config.xmlspring.datasource.test1.driverClassName  = Com.mysql.jdbc.Driverspring.datasource.test1.url  = Jdbc:mysql:// localhost:3306/test1?useunicode=true&characterencoding=utf-8  Spring.datasource.test1.username = Rootspring.datasource.test1.password  =< Span style= "COLOR: #000000" > rootspring.datasource.test2.driverClassName  = Com.mysql.jdbc.Driverspring.datasource.test2.url  = Jdbc:mysql:// localhost:3306/test2?useunicode=true&characterencoding=utf-8  Spring.datasource.test2.username = Rootspring.datasource.test2.password  = root 

A test1 library and a test2 library, where the test1-bit main library, in the process of use must be set up the main library, or will be error.
Data Source Configuration

@[email protected] (basepackages = "Com.neo.mapper.test1", Sqlsessiontemplateref = "Test1sqlsessiontemplate") Public classdatasource1config {@Bean (name= "Test1datasource") @ConfigurationProperties (prefix= "Spring.datasource.test1") @Primary PublicDataSource Testdatasource () {returndatasourcebuilder.create (). build (); } @Bean (Name= "Test1sqlsessionfactory") @Primary PublicSqlsessionfactory testsqlsessionfactory (@Qualifier ("Test1datasource") DataSource DataSource)throwsException {Sqlsessionfactorybean bean=NewSqlsessionfactorybean ();        Bean.setdatasource (DataSource); Bean.setmapperlocations (NewPathmatchingresourcepatternresolver (). Getresources ("Classpath:mybatis/mapper/test1/*.xml")); returnBean.getobject (); } @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); }}

The most important place is this one, layer by layer, first create DataSource, create Sqlsessionfactory in Create transaction, and finally wrap to sqlsessiontemplate. Where the mapper file address of the library needs to be developed, and the library-to-layer code

@MapperScan (basepackages = "Com.neo.mapper.test1", sqlsessiontemplateref  = "Test1sqlsessiontemplate")

This note refers to scanning the DAO layer and injecting the specified sqlsessiontemplate into the DAO layer. All @bean must be specified correctly by name.
DAO layer and XML layer
The DAO layer and XML need to be divided in different directories according to libraries authoring, for example: Test1 Library DAO layer under Com.neo.mapper.test1 package, Test2 library in Com.neo.mapper.test1

 Public Interface user1mapper {       List<UserEntity> getAll ();        Userentity GetOne (Long ID);     void Insert (userentity user);     void Update (userentity user);         void Delete (Long id);}

XML layer

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Com.neo.mapper.test1.User1Mapper" > <resultmap id= "baseresultmap" type= " Com.neo.entity.UserEntity "> <id column=" id "property=" id "jdbctype=" BIGINT "/> <result column=" UserName "property=" UserName "jdbctype=" VARCHAR "/> <result column=" PassWord "property=" PassWord "jdbctype=" V Archar "/> <result column=" user_sex "property=" Usersex "javatype=" Com.neo.enums.UserSexEnum "/> < Result column= "Nick_name" property= "nickname" jdbctype= "VARCHAR"/> </resultMap> <sql id= "Base_column_li St ">ID, UserName, PassWord, User_sex, Nick_name</sql> <select id= "GetAll" resultmap= "Baseresultmap" >SELECT<include refid= "Base_column_list"/>From users</select> <select id= "GetOne" parametertype= "Java.lang.Long" resultmap= "Baseresultmap" >SELECT<include refid= "Base_column_list"/>From users WHERE ID=#{id}</select> <insert id= "Insert" parametertype= "com.neo.entity.UserEntity" >INSERT into Users (username,password,user_sex) VALUES (#{username}, # {PassWord}, #{usersex})</insert> <update id= "Update" parametertype= "Com.neo.entity.UserEntity" >UPDATE users SET<ifTest= "UserName! = null" >username = #{username},</if> <ifTest= "PassWord! = null" >password = #{password},</if>Nick_name=#{nickname} WHERE ID=#{id}</update> <delete id= "delete" parametertype= "Java.lang.Long" >DELETE from users WHERE ID=#{id}</delete> </mapper>

Test
The test can be springboottest or put in a controller, where only the controller layer can be used

@RestControllerpublicclassUsercontroller {@AutowiredPrivateUser1mapper User1mapper; @AutowiredPrivateUser2mapper User2mapper; @RequestMapping ("/getusers")         PublicList<userentity>getusers () {List<UserEntity> users=User1mapper.getall (); returnusers; } @RequestMapping ("/getuser")         Publicuserentity GetUser (Long ID) {userentity user=User2mapper.getone (ID); returnuser; } @RequestMapping ("/add")         Public voidSave (userentity user) {User2mapper.insert (user); } @RequestMapping (Value= "Update")         Public voidUpdate (userentity user) {user2mapper.update (user); } @RequestMapping (Value= "/delete/{id}")         Public voidDelete (@PathVariable ("id"Long ID) {user1mapper.delete (ID); }}

The last source address is here: https://github.com/ityouknow/spring-boot-starter

Article Source: HTTP://MP.WEIXIN.QQ.COM/S/ESI8K3VOQKYL6PJ7ZBK6QW

More Learning resources: http://www.roncoo.com/course/list.html?courseName=spring+boot

Springboot--springboot+mybatis solution for multiple data sources

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.