文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2023-05-31 15:30

关注

一、摘要

这篇文章将介绍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());  } } }}

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 资料下载
  • 历年真题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     801人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     348人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     311人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     432人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     220人已做
    查看

相关文章

发现更多好内容
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯