Springboot integrates MyBatis, multi-data source, transaction, support Java-jar boot.

Source: Internet
Author: User

With a period of time springboot, before the configuration of MyBatis, in the packaging war under Tomcat normal, but the war is obsolete, now popular direct packaging jar thrown into the docker, but the jar started when the mapper scanning problems, We can only say that the way to integrate MyBatis is wrong.

This time the integration should be no problem caused by the loading sequence, used for a period of time, duly, recorded

Pom.xml

    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId> spring-boot-starter-parent</artifactid>        <version>1.5.4.RELEASE</version>        < Relativepath/> <!--lookup parent from repository--    </parent>        <dependency>            < Groupid>org.mybatis.spring.boot</groupid>            <artifactid>mybatis-spring-boot-starter</ artifactid>            <version>1.3.0</version>        </dependency>

APPLICATION.YML, support multiple data sources, how many to write how many, but this is a static multi-data source mode, you can dynamically go to the spring data source routing inside lost

spring:datasource:# readsize:1# Name:writedatasource TYPE:COM.ALIBABA.DRUID.POOL.DRUIDDATASOURC E write:driver-class-name:com.mysql.jdbc.driver Url:jdbc:mysql://localhost:3306/cloud?useunicode=tru E&characterencoding=utf-8&zerodatetimebehavior=converttonull&transformedbitisboolean=true&usessl=true username:root password:123 initialsize:10 maxactive:100 maxwait:60000 Minidle:5 timebetweenevictionrunsmillis:60000 minevictableidletimemillis:300000 ValidationQue Ry:select ' x ' testwhileidle:true testonborrow:false testonreturn:false poolpreparedstateme Nts:true maxpoolpreparedstatementperconnectionsize:20
Datasourceconfig.java
/*** Created by Zhenweilai on 2016/11/20.*/@Configuration @enabletransactionmanagement@mapperscan ("Com.lzw.**.dao")//mybatis Scan Public classDatasourceconfigImplementstransactionmanagementconfigurer {@Value ("${spring.datasource.type}")    Privateclass<?extendsDatasource>DatasourceType; @Primary @Bean (Name= "Writedatasource") @ConfigurationProperties (prefix= "Spring.datasource.write")     PublicDataSource Writedatasource () {returndatasourcebuilder.create (). Type (DatasourceType). build (); }    /*** How many will be configured from the library *@return     *///@Bean (name = "Readdatasource")//@ConfigurationProperties (prefix = "Spring.datasource.read")//Public DataSource Readdatasourceone () {//return Datasourcebuilder.create (). Type (DatasourceType). build ();//    }    /*** Abstractroutingdatasource This broken thing inherited Abstractdatasource, Abstractdatasource and realized DataSource * so you can just throw it to build sqlsess Ionfactory *@return     */@Bean ("Routingdatasource")//@Bean (name= "Routingdatasource", Initmethod = "Init", Destroymethod = "Close")     PublicMyroutingdatasource Datasourceproxy () {//int size = Integer.parseint (datasourcesize);Myroutingdatasource proxy =NewMyroutingdatasource (); Map<Object,Object> Datasourcemap =NewHashmap<>(); DataSource WriteSource=Writedatasource ();//DataSource Readsource = Getreaddatasource ();Datasourcemap.put (TargetDataSource.WRITE.getCode (), writesource);//Datasourcemap.put (TargetDataSource.READ.getCode (), readsource);Proxy.setdefaulttargetdatasource (Datasourcemap.get (TargetDataSource.WRITE.getCode ()));        Proxy.settargetdatasources (DATASOURCEMAP); returnproxy; } @Bean Publicsqlsessionfactory sqlsessionfactory () {Sqlsessionfactorybean bean=NewSqlsessionfactorybean ();        Bean.setdatasource (Datasourceproxy ()); Bean.settypealiasespackage ("COM.LZW"); Bean.setvfs (SPRINGBOOTVFS.class); //add an XML directoryResourcepatternresolver resolver =NewPathmatchingresourcepatternresolver (); Try{bean.setmapperlocations (resolver.getresources ("Classpath:**/mapper/**/*.xml")); returnBean.getobject (); } Catch(Exception e) {e.printstacktrace (); Throw NewRuntimeException (e); }    }    /*** Transaction configuration, considering multi-data source case *@return     */@Bean PublicPlatformtransactionmanager Txmanager () {return NewDatasourcetransactionmanager (Datasourceproxy ()); } @Override PublicPlatformtransactionmanager Annotationdriventransactionmanager () {returnTxmanager (); }}
Myroutingdatasource.java
/*** Created by Zhenweilai on 2016/11/22.*/ Public classMyroutingdatasourceextendsAbstractroutingdatasource {/*** Here can do simple load balancing, temporarily not used*///private int datasourceorder;//Private Atomicinteger count = new Atomicinteger (0);     PublicMyroutingdatasource () {}//Public myroutingdatasource (int _datasourceorder) {//this.datasourceorder = _datasourceorder;//    }    /*** This method will find the data source according to the returned key to the configuration file * *@return     */@OverrideprotectedObject Determinecurrentlookupkey () {returnDatasourcecontextholder.gettargetdatasource (); }}
Targetdatasource.java
/*** Created by Zhenweilai on 2016/11/22. * Configure read-write separation or multiple data sources*/ Public enumTargetdatasource {WRITE ("Write", "Main Library"), read ("read", "from Library"), Create ("Create", "Build Library"); Final PrivateString Code; Final PrivateString name; Targetdatasource (String _code,string _name) { This. Code =_code;  This. Name =_name; }     PublicString GetCode () {returnCode; }     PublicString GetName () {returnname; }     Public Staticstring Getnamebycode (String _code) { for(Targetdatasource item:TargetDataSource.values ()) {if(Item.getcode (). Equals (_code)) {returnItem.getname (); }        }        return""; }}

If you like, you can switch the data source using AOP annotations, but be aware of the misuse of AOP, coupled with the global unified AOP exception interception, and the spring AOP transaction, sequencing problems that may cause transaction failure, or failure of exception interception, or failure of the data source switchover.

AOP switching the data source will not work if it is opened first

/***/@Target (Elementtype.method) @Retention (retentionpolicy.runtime)public @Interface  datasourceswitch {    default "";}
Datasourcecontextholder.java
/*** Created by Zhenweilai on 2016/11/22. * Multiple data sources/read/write separation*/ Public classDatasourcecontextholder {Private Static FinalThreadlocal<string> datasourcelocal =NewThreadlocal<>();  Public StaticThreadlocal<string>getdatasourcelocal () {returndatasourcelocal; }    /*** from the library can have multiple*/     Public Static voidRead () {Datasourcelocal.set (TargetDataSource.READ.getCode ()); }    /*** The main library has only one*/     Public Static voidwrite () {Datasourcelocal.set (TargetDataSource.WRITE.getCode ()); }     Public StaticString Gettargetdatasource () {returnDatasourcelocal.get (); }}

Springboot integrates MyBatis, multi-data source, transaction, support Java-jar boot.

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.