广告
返回顶部
首页 > 资讯 > 精选 >Spring3 整合MyBatis3 配置多数据源动态选择SqlSessionFactory详细教程
  • 786
分享到

Spring3 整合MyBatis3 配置多数据源动态选择SqlSessionFactory详细教程

springmybatis多数据源 2023-05-31 15:05:02 786人浏览 泡泡鱼
摘要

一、摘要这篇文章将介绍spring整合mybatis 如何完成sqlSessionFactory的动态切换的。并且会简单的介绍下MyBatis整合Spring中的官方的相关代码。Spring整合MyBatis切换SqlSessionFact

一、摘要

这篇文章将介绍spring整合mybatis 如何完成sqlSessionFactory的动态切换的。并且会简单的介绍下MyBatis整合Spring中的官方的相关代码。

Spring整合MyBatis切换SqlSessionFactory有两种方法

第一、 继承SqlSessionDaoSupport,重写获取SqlSessionFactory的方法。

第二、继承SqlSessionTemplate 重写getSqlSessionFactory、getConfiguration和SqlSessionInterceptor这个拦截器。其中最为关键还是继承SqlSessionTemplate 并重写里面的方法。

而Spring整合MyBatis也有两种方式,一种是配置MapperFactoryBean,另一种则是利用MapperScannerConfigurer进行扫描接口或包完成对象的自动创建。相对来说后者更方便些。

MapperFactoryBean继承了SqlSessionDaoSupport也就是动态切换SqlSessionFactory的第一种方法,我们需要重写和实现SqlSessionDaoSupport方法,或者是继承MapperFactoryBean来重写覆盖相关方法。如果利用MapperScannerConfigurer的配置整合来切换SqlSessionFactory,那么我们就需要继承SqlSessionTemplate,重写上面提到的方法。在整合的配置中很多地方都是可以注入SqlSessionTemplate代替SqlSessionFactory的注入的。因为SqlSessionTemplate的创建也是需要注入SqlSessionFactory的。

二、实现代码

继承SqlSessionTemplate 重写getSqlSessionFactory、getConfiguration和SqlSessionInterceptor

package com.hoo.framework.mybatis.support;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;public class CustomSqlSessionTemplate 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 void setDefaultTargetSqlSessionFactory(SqlSessionFactory defaultTargetSqlSessionFactory) { this.defaultTargetSqlSessionFactory = defaultTargetSqlSessionFactory; } public CustomSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); } public CustomSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) { this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration()  .getEnvironment().getDataSource(), true)); } public CustomSqlSessionTemplate(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(CustomerContextHolder.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; }  public <T> T selectOne(String statement) { return this.sqlSessionProxy.<T> selectOne(statement); }  public <T> T selectOne(String statement, Object parameter) { return this.sqlSessionProxy.<T> selectOne(statement, parameter); }  public <K, V> Map<K, V> selectMap(String statement, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey); }  public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey); }  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); }  public <E> List<E> selectList(String statement) { return this.sqlSessionProxy.<E> selectList(statement); }  public <E> List<E> selectList(String statement, Object parameter) { return this.sqlSessionProxy.<E> selectList(statement, parameter); }  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds); }  public void select(String statement, ResultHandler handler) { this.sqlSessionProxy.select(statement, handler); }  public void select(String statement, Object parameter, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, handler); }  public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, rowBounds, handler); }  public int insert(String statement) { return this.sqlSessionProxy.insert(statement); }  public int insert(String statement, Object parameter) { return this.sqlSessionProxy.insert(statement, parameter); }  public int update(String statement) { return this.sqlSessionProxy.update(statement); }  public int update(String statement, Object parameter) { return this.sqlSessionProxy.update(statement, parameter); }  public int delete(String statement) { return this.sqlSessionProxy.delete(statement); }  public int delete(String statement, Object parameter) { return this.sqlSessionProxy.delete(statement, parameter); }  public <T> T getMapper(Class<T> type) { return getConfiguration().getMapper(type, this); }  public void commit() { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); }  public void commit(boolean force) { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); }  public void rollback() { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); }  public void rollback(boolean force) { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); }  public void close() { throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession"); }  public void clearCache() { this.sqlSessionProxy.clearCache(); }  public Connection getConnection() { return this.sqlSessionProxy.getConnection(); }  public List<BatchResult> flushStatements() { return this.sqlSessionProxy.flushStatements(); }  private class SqlSessionInterceptor implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  final SqlSession sqlSession = getSqlSession(   CustomSqlSessionTemplate.this.getSqlSessionFactory(),   CustomSqlSessionTemplate.this.executorType,    CustomSqlSessionTemplate.this.exceptionTranslator);  try {  Object result = method.invoke(sqlSession, args);  if (!isSqlSessionTransactional(sqlSession, CustomSqlSessionTemplate.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 (CustomSqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {   Throwable translated = CustomSqlSessionTemplate.this.exceptionTranslator   .translateExceptionIfPossible((PersistenceException) unwrapped);   if (translated != null) {   unwrapped = translated;   }  }  throw unwrapped;  } finally {  closeSqlSession(sqlSession, CustomSqlSessionTemplate.this.getSqlSessionFactory());  } } }}

--结束END--

本文标题: Spring3 整合MyBatis3 配置多数据源动态选择SqlSessionFactory详细教程

本文链接: https://www.lsjlt.com/news/226763.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作