中文字幕日韩精品一区二区免费_精品一区二区三区国产精品无卡在_国精品无码专区一区二区三区_国产αv三级中文在线

在Spring項(xiàng)目中使用Mybatis如何實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源

這篇文章將為大家詳細(xì)講解有關(guān)在Spring項(xiàng)目中使用 Mybatis 如何實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

創(chuàng)新互聯(lián)擁有網(wǎng)站維護(hù)技術(shù)和項(xiàng)目管理團(tuán)隊(duì),建立的售前、實(shí)施和售后服務(wù)體系,為客戶提供定制化的成都做網(wǎng)站、網(wǎng)站制作、網(wǎng)站維護(hù)、成都機(jī)柜租用解決方案。為客戶網(wǎng)站安全和日常運(yùn)維提供整體管家式外包優(yōu)質(zhì)服務(wù)。我們的網(wǎng)站維護(hù)服務(wù)覆蓋集團(tuán)企業(yè)、上市公司、外企網(wǎng)站、商城建設(shè)、政府網(wǎng)站等各類型客戶群體,為全球近千家企業(yè)提供全方位網(wǎng)站維護(hù)、服務(wù)器維護(hù)解決方案。

實(shí)現(xiàn)思路是:

第一步,實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源:配置兩個(gè)DataSource,配置兩個(gè)SqlSessionFactory指向兩個(gè)不同的DataSource,兩個(gè)SqlSessionFactory都用一個(gè)SqlSessionTemplate,同時(shí)重寫Mybatis提供的SqlSessionTemplate類,最后配置Mybatis自動掃描。

第二步,利用aop切面,攔截dao層所有方法,因?yàn)閐ao層方法命名的特點(diǎn),比如所有查詢sql都是select開頭,或者get開頭等等,攔截這些方法,并把當(dāng)前數(shù)據(jù)源切換至從庫。

spring中配置如下:

主庫數(shù)據(jù)源配置:

 <bean id="masterDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">2 <property name="driverClass" value="${master_MySQL_jdbc_driver}" />
 <property name="jdbcUrl" value="${master_mysql_jdbc_url}" />
 <property name="user" value="${master_mysql_jdbc_user}" />
 <property name="password" value="${master_mysql_jdbc_password}" />
 </bean>

從庫數(shù)據(jù)源配置:

 <bean id="masterDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
 <property name="driverClass" value="${slave_mysql_jdbc_driver}" />
 <property name="jdbcUrl" value="${slave_mysql_jdbc_url}" />
 <property name="user" value="${slave_mysql_jdbc_user}" />
 <property name="password" value="${slave_mysql_jdbc_password}" />
 </bean>

主庫SqlSessionFactory配置:

 <bean id="masterSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="masterDataSource" />
 <property name="mapperLocations" value="classpath:com/sincetimes/slg/dao/*.xml"/>
 </bean>

從庫SqlSessionFactory配置:

 <bean id="slaveSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="slaveDataSource" />
 <property name="mapperLocations" value="classpath:com/sincetimes/slg/dao/*.xml"/>
 </bean>

兩個(gè)SqlSessionFactory使用同一個(gè)SqlSessionTemplate配置:

 <bean id="MasterAndSlaveSqlSessionTemplate" class="com.sincetimes.slg.framework.core.DynamicSqlSessionTemplate">
 <constructor-arg index="0" ref="masterSqlSessionFactory" />
 <property name="targetSqlSessionFactorys">
 <map> 
 <entry value-ref="masterSqlSessionFactory" key="master"/> 
 <entry value-ref="slaveSqlSessionFactory" key="slave"/> 
 </map> 
 </property>
 </bean>

配置Mybatis自動掃描dao

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 <property name="basePackage" value="com.sincetimes.slg.dao" />
 <property name="sqlSessionTemplateBeanName" value="MasterAndSlaveSqlSessionTemplate" />
 </bean>

自己重寫了SqlSessionTemplate代碼如下:

package com.sincetimes.slg.framework.core;
import static java.lang.reflect.Proxy.newProxyInstance;
import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable;
import static org.mybatis.spring.SqlSessionUtils.closeSqlSession;
import static org.mybatis.spring.SqlSessionUtils.getSqlSession;
import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.MyBatisExceptionTranslator;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.util.Assert;
import com.sincetimes.slg.framework.util.SqlSessionContentHolder;
/**
 * 
 * TODO 重寫SqlSessionTemplate
 * @author ccg
 * @version 1.0
 * Created 2017年4月21日 下午3:15:15
 */
public class DynamicSqlSessionTemplate extends SqlSessionTemplate {
 private final SqlSessionFactory sqlSessionFactory;
 private final ExecutorType executorType;
 private final SqlSession sqlSessionProxy;
 private final PersistenceExceptionTranslator exceptionTranslator;
 private Map<Object, SqlSessionFactory> targetSqlSessionFactorys;
 private SqlSessionFactory defaultTargetSqlSessionFactory;
 public void setTargetSqlSessionFactorys(Map<Object, SqlSessionFactory> targetSqlSessionFactorys) {
 this.targetSqlSessionFactorys = targetSqlSessionFactorys;
 }
 public Map<Object, SqlSessionFactory> getTargetSqlSessionFactorys(){
 return targetSqlSessionFactorys;
 }
 public void setDefaultTargetSqlSessionFactory(SqlSessionFactory defaultTargetSqlSessionFactory) {
 this.defaultTargetSqlSessionFactory = defaultTargetSqlSessionFactory;
 }
 public DynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
 this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
 }
 public DynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
 this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration()
 .getEnvironment().getDataSource(), true));
 }
 public DynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
 PersistenceExceptionTranslator exceptionTranslator) {
 super(sqlSessionFactory, executorType, exceptionTranslator);
 this.sqlSessionFactory = sqlSessionFactory;
 this.executorType = executorType;
 this.exceptionTranslator = exceptionTranslator;
 this.sqlSessionProxy = (SqlSession) newProxyInstance(
 SqlSessionFactory.class.getClassLoader(),
 new Class[] { SqlSession.class }, 
 new SqlSessionInterceptor());
 this.defaultTargetSqlSessionFactory = sqlSessionFactory;
 }
 @Override
 public SqlSessionFactory getSqlSessionFactory() {
 SqlSessionFactory targetSqlSessionFactory = targetSqlSessionFactorys.get(SqlSessionContentHolder.getContextType());
 if (targetSqlSessionFactory != null) {
 return targetSqlSessionFactory;
 } else if (defaultTargetSqlSessionFactory != null) {
 return defaultTargetSqlSessionFactory;
 } else {
 Assert.notNull(targetSqlSessionFactorys, "Property 'targetSqlSessionFactorys' or 'defaultTargetSqlSessionFactory' are required");
 Assert.notNull(defaultTargetSqlSessionFactory, "Property 'defaultTargetSqlSessionFactory' or 'targetSqlSessionFactorys' are required");
 }
 return this.sqlSessionFactory;
 }
 @Override
 public Configuration getConfiguration() {
 return this.getSqlSessionFactory().getConfiguration();
 }
 public ExecutorType getExecutorType() {
 return this.executorType;
 }
 public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
 return this.exceptionTranslator;
 }
 /**
 * {@inheritDoc}
 */
 public <T> T selectOne(String statement) {
 return this.sqlSessionProxy.<T> selectOne(statement);
 }
 /**
 * {@inheritDoc}
 */
 public <T> T selectOne(String statement, Object parameter) {
 return this.sqlSessionProxy.<T> selectOne(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
 return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey);
 }
 /**
 * {@inheritDoc}
 */
 public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
 return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey);
 }
 /**
 * {@inheritDoc}
 */
 public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
 return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds);
 }
 /**
 * {@inheritDoc}
 */
 public <E> List<E> selectList(String statement) {
 return this.sqlSessionProxy.<E> selectList(statement);
 }
 /**
 * {@inheritDoc}
 */
 public <E> List<E> selectList(String statement, Object parameter) {
 return this.sqlSessionProxy.<E> selectList(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
 return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds);
 }
 /**
 * {@inheritDoc}
 */
 public void select(String statement, ResultHandler handler) {
 this.sqlSessionProxy.select(statement, handler);
 }
 /**
 * {@inheritDoc}
 */
 public void select(String statement, Object parameter, ResultHandler handler) {
 this.sqlSessionProxy.select(statement, parameter, handler);
 }
 /**
 * {@inheritDoc}
 */
 public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
 this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
 }
 /**
 * {@inheritDoc}
 */
 public int insert(String statement) {
 return this.sqlSessionProxy.insert(statement);
 }
 /**
 * {@inheritDoc}
 */
 public int insert(String statement, Object parameter) {
 return this.sqlSessionProxy.insert(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public int update(String statement) {
 return this.sqlSessionProxy.update(statement);
 }
 /**
 * {@inheritDoc}
 */
 public int update(String statement, Object parameter) {
 return this.sqlSessionProxy.update(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public int delete(String statement) {
 return this.sqlSessionProxy.delete(statement);
 }
 /**
 * {@inheritDoc}
 */
 public int delete(String statement, Object parameter) {
 return this.sqlSessionProxy.delete(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public <T> T getMapper(Class<T> type) {
 return getConfiguration().getMapper(type, this);
 }
 /**
 * {@inheritDoc}
 */
 public void commit() {
 throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void commit(boolean force) {
 throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void rollback() {
 throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void rollback(boolean force) {
 throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void close() {
 throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void clearCache() {
 this.sqlSessionProxy.clearCache();
 }
 /**
 * {@inheritDoc}
 */
 public Connection getConnection() {
 return this.sqlSessionProxy.getConnection();
 }
 /**
 * {@inheritDoc}
 * @since 1.0.2
 */
 public List<BatchResult> flushStatements() {
 return this.sqlSessionProxy.flushStatements();
 }
 /**
 * Proxy needed to route MyBatis method calls to the proper SqlSession got from Spring's Transaction Manager It also
 * unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to pass a {@code PersistenceException} to
 * the {@code PersistenceExceptionTranslator}.
 */
 private class SqlSessionInterceptor implements InvocationHandler {
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 final SqlSession sqlSession = getSqlSession(
  DynamicSqlSessionTemplate.this.getSqlSessionFactory(),
  DynamicSqlSessionTemplate.this.executorType, 
  DynamicSqlSessionTemplate.this.exceptionTranslator);
 try {
 Object result = method.invoke(sqlSession, args);
 if (!isSqlSessionTransactional(sqlSession, DynamicSqlSessionTemplate.this.getSqlSessionFactory())) {
  // force commit even on non-dirty sessions because some databases require
  // a commit/rollback before calling close()
  sqlSession.commit(true);
 }
 return result;
 } catch (Throwable t) {
 Throwable unwrapped = unwrapThrowable(t);
 if (DynamicSqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
  Throwable translated = DynamicSqlSessionTemplate.this.exceptionTranslator
  .translateExceptionIfPossible((PersistenceException) unwrapped);
  if (translated != null) {
  unwrapped = translated;
  }
 }
 throw unwrapped;
 } finally {
 closeSqlSession(sqlSession, DynamicSqlSessionTemplate.this.getSqlSessionFactory());
 }
 }
 }
}

SqlSessionContentHolder類代碼如下:

package com.sincetimes.slg.framework.util;
public abstract class SqlSessionContentHolder {
 public final static String SESSION_FACTORY_MASTER = "master";
 public final static String SESSION_FACTORY_SLAVE = "slave";
 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); 
 public static void setContextType(String contextType) { 
 contextHolder.set(contextType); 
 } 
 public static String getContextType() { 
 return contextHolder.get(); 
 } 
 public static void clearContextType() { 
 contextHolder.remove(); 
 } 
}

最后就是寫切面去對dao所有方法進(jìn)行處理了,代碼很簡單如下:

package com.sincetimes.slg.framework.core;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import com.sincetimes.slg.framework.util.SqlSessionContentHolder;
@Aspect
public class DynamicDataSourceAspect {
 @Pointcut("execution( * com.sincetimes.slg.dao.*.*(..))")
 public void pointCut(){
 }
 @Before("pointCut()")
 public void before(JoinPoint jp){
 String methodName = jp.getSignature().getName(); 
 //dao方法查詢走從庫
 if(methodName.startsWith("query") || methodName.startsWith("get") || methodName.startsWith("count") || methodName.startsWith("list")){
 SqlSessionContentHolder.setContextType(SqlSessionContentHolder.SESSION_FACTORY_SLAVE);
 }else{
 SqlSessionContentHolder.setContextType(SqlSessionContentHolder.SESSION_FACTORY_MASTER);
 }
 }
}

關(guān)于在Spring項(xiàng)目中使用 Mybatis 如何實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

分享名稱:在Spring項(xiàng)目中使用Mybatis如何實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源
標(biāo)題鏈接:http://www.rwnh.cn/article16/gdgsgg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號網(wǎng)站策劃、商城網(wǎng)站營銷型網(wǎng)站建設(shè)、品牌網(wǎng)站制作、自適應(yīng)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)
竹山县| 兴业县| 武定县| 马关县| 罗平县| 南康市| 武宁县| 邯郸市| 原阳县| 绥宁县| 松原市| 三台县| 罗田县| 阿鲁科尔沁旗| 天津市| 张家口市| 峨眉山市| 襄汾县| 凤翔县| 宁化县| 鄂温| 墨竹工卡县| 金溪县| 永靖县| 济宁市| 天祝| 钦州市| 女性| 剑川县| 射阳县| 施秉县| 广丰县| 玉门市| 娄烦县| 平度市| 定结县| 信阳市| 颍上县| 柳河县| 阳春市| 武胜县|