


Spring and Mybatis are combined to realize multi-data source switching function
Without further ado, the key code is as follows:
1. Code: DbContextHolder
public class DbContextHolder { //线程安全的ThreadLocal private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setDbType(String dbType) { contextHolder.set(dbType); } public static String getDbType() { return ((String)contextHolder.get()); } public static void clearDbType() { contextHolder.remove(); } }
2. Code: DynamicDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override public Object determineCurrentLookupKey() { return DbContextHolder.getDbType(); } }
3. Code: spring.xml
<!-- 数据源属性配置文件 --> <context:property-placeholder location="classpath:ibatis.properties" /> <bean id="jksh" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${driver.jksh}" /> <property name="url" value="${url.jksh}" /> <property name="username" value="${username.jksh}" /> <property name="password" value="${password.jksh}" /> <!-- Connection Pooling Info --> <property name="maxIdle" value="${maxIdle.jksh}" /> <property name="maxActive" value="${maxActive.jksh}" /> <property name="defaultAutoCommit" value="false" /> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis.jksh}" /> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis.jksh}" /> </bean> <bean id="jclt" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${driver.jclt}" /> <property name="url" value="${url.jclt}" /> <property name="username" value="${username.jclt}" /> <property name="password" value="${password.jclt}" /> <!-- Connection Pooling Info --> <property name="maxIdle" value="${maxIdle.jclt}" /> <property name="maxActive" value="${maxActive.jclt}" /> <property name="defaultAutoCommit" value="false" /> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis.jclt}" /> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis.jclt}" /> </bean> <bean id="dataSource" class="com.jclt.service.commons.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="jksh" value-ref="jksh" /> <entry key="jclt" value-ref="jclt" /> </map> </property> <property name="defaultTargetDataSource" ref="jksh" /> </bean>
4. Code: main method
import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import com.jclt.service.commons.DbContextHolder; import com.jclt.service.model.User; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; public class Text { /** * @param args */ public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("client-beans.xml"); DbContextHolder.setDbType("jclt"); String res="src/main/resources/ibatis-config.xml"; DataSource datasource=(DataSource) appContext.getBean("dataSource"); SqlSessionFactoryBean bean=new SqlSessionFactoryBean(); bean.setDataSource(datasource); Resource resource=new FileSystemResource(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=new SqlSessionFactoryBean(); bean1.setDataSource(datasource1); Resource resource1=new FileSystemResource(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(); } } }
The above is the combination of Spring and Mybatis introduced by the editor to implement the multi-data source switching function. I hope it will be helpful to everyone. If you have any questions, please let me know. Leave a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!
For more related articles on the combination of Spring and Mybatis to achieve multi-data source switching function, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...
