>  기사  >  Java  >  Spring과 Mybatis를 결합하여 다중 데이터 소스 전환 기능 구현

Spring과 Mybatis를 결합하여 다중 데이터 소스 전환 기능 구현

高洛峰
高洛峰원래의
2017-01-24 10:17:271175검색

더 이상 고민하지 않아도 키 코드는 다음과 같습니다.

1. 코드: 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. 🎜>

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
public Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
}

3. 코드: 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>

코드: 메인 메소드

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();
}
}
}

위는 멀티 데이터 소스 전환 기능을 구현하기 위해 에디터가 소개한 Spring과 Mybatis의 조합입니다. , 메시지를 남겨주시면 편집자가 제때에 답변해 드리겠습니다. 또한 PHP 중국어 웹사이트를 지원해 주신 모든 분들께 감사드립니다!

다중 데이터 소스 전환 기능을 구현하기 위한 Spring과 Mybatis의 조합에 대한 더 많은 관련 기사를 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.