Spring+mybatis Multiple data source switching

Source: Internet
Author: User
Tags findone

Dbcontextholder
 Public classDbcontextholder {//thread-Safe threadlocal    Private Static FinalThreadlocal<string> Contextholder =NewThreadlocal<string>();  Public Static voidSetdbtype (String dbType) {contextholder.set (dbType); }      Public StaticString Getdbtype () {return(String) contextholder.get ()); }     Public Static voidCleardbtype () {contextholder.remove (); } }
Dynamicdatasource
Importpublicclassextends  abstractroutingdatasource {     @Override      Public Object Determinecurrentlookupkey () {        return  dbcontextholder.getdbtype ();    }} 
Spring.xml
<!--Data Source Properties configuration file -    <Context:property-placeholder Location= "Classpath:ibatis.properties" />      <BeanID= "Jksh"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">        <!--Connection Info -        < Propertyname= "Driverclassname"value= "${driver.jksh}" />        < Propertyname= "url"value= "${url.jksh}" />        < Propertyname= "username"value= "${username.jksh}" />        < Propertyname= "Password"value= "${password.jksh}" />         <!--Connection Pooling Info -        < Propertyname= "Maxidle"value= "${maxidle.jksh}" />        < Propertyname= "Maxactive"value= "${maxactive.jksh}" />        < Propertyname= "Defaultautocommit"value= "false" />        < Propertyname= "Timebetweenevictionrunsmillis"value= "${timebetweenevictionrunsmillis.jksh}" />        < Propertyname= "Minevictableidletimemillis"value= "${minevictableidletimemillis.jksh}" />    </Bean>     <BeanID= "JCLT"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">        <!--Connection Info -        < Propertyname= "Driverclassname"value= "${DRIVER.JCLT}" />        < Propertyname= "url"value= "${URL.JCLT}" />        < Propertyname= "username"value= "${USERNAME.JCLT}" />        < Propertyname= "Password"value= "${PASSWORD.JCLT}" />         <!--Connection Pooling Info -        < Propertyname= "Maxidle"value= "${MAXIDLE.JCLT}" />        < Propertyname= "Maxactive"value= "${MAXACTIVE.JCLT}" />        < Propertyname= "Defaultautocommit"value= "false" />        < Propertyname= "Timebetweenevictionrunsmillis"value= "${TIMEBETWEENEVICTIONRUNSMILLIS.JCLT}" />        < Propertyname= "Minevictableidletimemillis"value= "${MINEVICTABLEIDLETIMEMILLIS.JCLT}" />    </Bean>      <BeanID= "DataSource"class= "Com.jclt.service.commons.DynamicDataSource">        < Propertyname= "Targetdatasources">            <MapKey-type= "Java.lang.String">                <entryKey= "Jksh"Value-ref= "Jksh" />                <entryKey= "JCLT"Value-ref= "JCLT" />            </Map>        </ Property>        < Propertyname= "Defaulttargetdatasource"ref= "Jksh" />    </Bean>
Main method
ImportJavax.sql.DataSource;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportOrg.springframework.core.io.FileSystemResource;ImportOrg.springframework.core.io.Resource;ImportCom.jclt.service.commons.DbContextHolder;ImportCom.jclt.service.model.User;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.mybatis.spring.SqlSessionFactoryBean; Public classText {/**     * @paramargs*/     Public Static voidMain (string[] args) {ApplicationContext appContext=NewClasspathxmlapplicationcontext ("Client-beans.xml"); Dbcontextholder.setdbtype ("JCLT"); String Res= "Src/main/resources/ibatis-config.xml"; DataSource DataSource= (DataSource) appcontext.getbean ("DataSource"); Sqlsessionfactorybean Bean=NewSqlsessionfactorybean ();        Bean.setdatasource (DataSource); Resource Resource=NewFilesystemresource (RES);        Bean.setconfiglocation (Resource); Try{sqlsessionfactory sessionfactory=Bean.getobject (); Sqlsession Session=sessionfactory.opensession (); User User=session.selectone ("Com.jclt.service.Dao.readJKSH.findOne");        System.out.println (User.getname ()); } Catch(Exception e) {e.printstacktrace (); } dbcontextholder.setdbtype ("Jksh"); String res1= "Src/main/resources/ibatis-config.xml"; DataSource Datasource1= (DataSource) appcontext.getbean ("DataSource"); Sqlsessionfactorybean Bean1=NewSqlsessionfactorybean ();        Bean1.setdatasource (Datasource1); Resource Resource1=NewFilesystemresource (RES1);         Bean1.setconfiglocation (Resource1); Try{sqlsessionfactory sessionfactory=Bean.getobject (); Sqlsession Session=sessionfactory.opensession (); User User=session.selectone ("Com.jclt.service.Dao.readJKSH.findOne");        System.out.println (User.getname ()); } Catch(Exception e) {e.printstacktrace (); }    } }

This article transferred from: http://www.oschina.net/code/snippet_347813_12525

Spring+mybatis Multiple data source switching

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.