Spring+mybatis Configuration of multiple databases

Source: Internet
Author: User
Tags aop

Scenario: How do I configure two databases in a project built in Spring+mybatis?

in fact, it is not much difficult things, as long as the configuration is well-equipped, all problems will be solved, nonsense not to say, and see

Configure as follows ...


Configuration One: jdbc.properties

Configure two databases: MyUser and myitem

Myuser.jdbc.driver=com.mysql.jdbc.drivermyuser.jdbc.url=jdbc:mysql://192.168.1.100:3306/myuser?useunicode=true &zeroDateTimeBehavior=convertToNull&characterEncoding=utf8&autoReconnect=true& Allowmultiqueries=truemyuser.jdbc.username=rootmyuser.jdbc.password=123456myitem.jdbc.driver= com.mysql.jdbc.drivermyitem.jdbc.url=jdbc:mysql://192.168.1.100:3306/myitem?useunicode=true& zerodatetimebehavior=converttonull&characterencoding=utf8&autoreconnect=true&allowmultiqueries= truemyitem.jdbc.username=rootmyitem.jdbc.password=123456

Configuration two: Applicationcontext.xml

Configuration:

Two data sources (Myuserdatasource and Myitemdatasource),

A dynamic datasource (Dynamicdatasource);

      <!--  Database connection pool 1 :myuser-->    <bean  id= "Myuserdatasource"  class= "Com.jolbox.bonecp.BoneCPDataSource"          destroy-method= "Close" >        <!--  Database driver  -->        <property name= "DriverClass"  value= "$ {myuser.jdbc.driver} " />        <!--  corresponding driver Jdbcurl  -->        <property name= "JdbcUrl"  value= "${ Myuser.jdbc.url} " />        <!--  user name for database  -->         <property name= "username"  value= "${ Myuser.jdbc.username} " />        <!--  password  --of the database >      &nbsP; <property name= "Password"  value= "${myuser.jdbc.password}"  />         <!--  Check the interval between idle connections in the database connection pool, in units of minutes, default: 240, set to 0 -->   if you want to cancel       <property name= "Idleconnectiontestperiod"  value= " /" >        <!--  Unused links in the connection pool maximum survival time, unit is minute, default value: 60, if you want to live forever set to 0  -->        <property name= "IdleMaxAge"  value= "30 " />        <!--  Maximum number of connections per partition  -->         <property name= "Maxconnectionsperpartition"  value= " " />        <!--  Minimum number of connections per partition  -->         <property name= "Minconnectionsperpartition"  value= "5"  />     </bean>    <!--  Database connection pool 2 :myitem-->    <bean id= "Myitemdatasource"  class= "Com.jolbox.bonecp.BoneCPDataSource"          destroy-method= "Close" >        <!--  Database driver  -->         <property name= "Driverclass"  value= "${ Myitem.dbc.driver} " />        <!--  corresponding driver jdbcurl - ->        <property name= "JdbcUrl"  value= "${ Myitem.jdbc.url} " />        <!--  user name for database  -->         <property name= "username"  value= "${ Myitem.jdbc.username} " />        <!--  password  --of the database >         <property name= "Password"  value= "${myitem.jdbc.password}"  />         <!--  Check the interval between idle connections in the database connection pool, in units of minutes, default: 240, set to 0 -->    if you want to cancel      <property name= "Idleconnectiontestperiod"  value= " />"         <!--  Unused links in the connection pool maximum survival time, unit is minute, default value: 60, if you want to live forever set to 0 -- >        <property name= "IdleMaxAge"  value= " /" >        <!--  Maximum number of connections per partition  -->         <property name= "Maxconnectionsperpartition"  value= " />"         <!--  Minimum number of connections per partition  -->         <property name= "Minconnectionsperpartition"  value= "5"  />     </bean>            <!--  Database connection pool  -->     <bean id= "Dynamicdatasource"  class= " Com.wupao.sso.dynamicdatasource.DynamicDataSource ">        < Property name= "Targetdatasources" >             <map key-type= "Java.lang.String" >                 <entry value-ref= "Myuserdatasource"  key= "MyUserDataSource"/ >                <entry  value-ref= "Myitemdatasource"  key= "Myitemdatasource"/>             </map>        </property> <!--          &Lt;property name= "Defaulttargetdatasource"  ref= "Myuserdatasource"/> Use MyUserDataSource data source by default   -->    </bean>

There are children's shoes may ask: Dynamicdatasource This class is going on?

Don't worry, this class is a custom class that must inherit: Abstractroutingdatasource this abstract class, and rewrite

Abstractroutingdatasource method, the Dynamic data source will not take effect.

The code is as follows:

/** * Custom Dynamic Data source, inherit Abstractroutingdatasource abstract class, * override Determinecurrentlookupkey method * @author Root */public class        Dynamicdatasource extends Abstractroutingdatasource {@Override protected Object Determinecurrentlookupkey () {    return Dbcontextholder.getdbtype (); }}

Q: How does that thing manage? don't worry, keep looking down ...

Configuration three: Applicationcontext-transaction.xml

<!--  Define transaction manager  -->    <bean id= "TransactionManager"          class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >        <property name= "DataSource"  ref= " Dynamicdatasource " />    </bean>    <!--  Define transaction policy  -->    <tx:advice id= "Txadvice"  transaction-manager= " TransactionManager ">        <tx:attributes>             <!--all methods that start with query are read-only  -->             <tx:method name= "query*"  read-only= "true"  />            <!--Other methods use the default transaction policy  -- >       &nBsp;    <tx:method name= "*"  />         </tx:attributes>    </tx:advice>    <aop:config >        <!--pointcut element defines a pointcut, the first asterisk in execution   the return type to match the method ,             Here the asterisk indicates that all return types are matched.  com.abc.dao.*.* (..) Indicates all             of classes that match the Com.simple.mybatis.service package    method  -->        <aop:pointcut id= "MyPointcut " expression=" Execution (* com.simple.sso.service.*.* (..)) "  />        <!--apply a defined transaction-handling policy to the above pointcuts  -->         <aop:advisor advice-ref= "Txadvice"  pointcut-ref= "MyPointcut"  />    </aop:config>

Q: So how does sqlsessionfactory get the data source? continue to configure ...

Configuration four: Applicationcontext-mybatis.xml

  <!--  Define MyBatis's sqlsessionfactory -->    <bean id= " Sqlsessionfactory " class=" Org.mybatis.spring.SqlSessionFactoryBean ">         <!--  Define data source  -->        <property  name= "DataSource"  ref= "Dynamicdatasource"  />         <!--  Specify mybatis global configuration file  -->        <property  name= "Configlocation"  value= "Classpath:mybatis/mybatis-config.xml" ></property>                 <!--  Scan all XML files in the Mappers directory and subdirectories  --><!--            <property name= "Mapperlocations"  value= "Classpath:mybatis/mappers/**/*.xml"  /> -- >                    <!--  Alias scan package  -->           <property name= "TypeAliasesPackage"   Value= "Com.simple.sso.pojo"/>    </bean>

Here, in fact, the configuration has been configured.

Q: So how do you use it in your code? For example, the data to be inserted into which database to insert it? How do I make sure the data is the database I want to insert?

We all know to insert the data first is to generate the entity classes and tables corresponding to the data encapsulated in the entity class, through mapping relationships and annotations to insert data into the table, so the bright spot is here, the above problem is self-evident.

Add annotations on the annotation on the entity class:

For example: The MyUser database has the user table, specifying: database name. Table name (emphasis!!!) )

@Table (name = "Myuser.user") public class User {@Id @GeneratedValue (strategy = generationtype.identity) Private I Nteger id;//User ID @Length (min = 2, max = $, message = "account name is 2-20 bits, composed of Chinese characters, letters (not case), numbers, or underscores! ") Private String loginname;//user name

When this is specified, when data is inserted into the Myuser.user table in the code, the encapsulated user object is passed as a parameter to the Saveuser (user user) method and is automatically inserted into the user table in the MyUser library.

Q: What if there is a user table in the myitem table? How do I insert data into the user table of myitem?

Answer: Ditto!

@Table (name = "Myitem.user") public class Itemuser {@Id @GeneratedValue (strategy = generationtype.identity) Priva Te Integer id;//User id @Length (min = 2, max = +, message = "account name is 2-20 bits, made up of Chinese characters, letters (not case), numbers, or underscores!) ") Private String loginname;//user name

See here, I believe you have some understanding, I wish you a successful configuration!

This article is from the "Simple Life" blog, so be sure to keep this source http://simplelife.blog.51cto.com/9954761/1706542

Spring+mybatis Configuration of multiple databases

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.