主要思路:

DataSource --> SqlSessionFactory --> SqlSessionTemplate

第一方式:

定义多套  DataSource --> SqlSessionFactory --> SqlSessionTemplate

https://blog.csdn.net/u012343297/article/details/78835185

每套放置在不同的 package 下面,使用来确定bean  @Qualifier

https://blog.csdn.net/neosmith/article/details/61202084

使用 AOP 动态切换

第二种方式:

在不影响原来的一套的设计前提下,增加对另一个库的访问。

1 配置一个新的 SqlSessionTemplate

@Bean(name = "uumsqlSessionTemplate")
public SqlSessionTemplate uumsqlSessionTemplate() throws Exception {
Properties props = new Properties();
props.put("driverClassName", driverClassName);
props.put("url", dbUrl);
props.put("username", userName);
props.put("password", password);
DataSource dataSource = DruidDataSourceFactory.createDataSource(props); SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/mapping/*.xml"));
bean.setDataSource(dataSource);
return new SqlSessionTemplate(bean.getObject());
}

2. 写一个 mapper, 使用 注解@Select 或者 写一个对应的 xml

public interface CustomUUMMapper {
@Select("SELECT role.`name` as description, role.`code` as rolename from uum_t_role as role where role.id in " +
"(SELECT ur.role_id from uum_r_user_role as ur where ur.user_id in " +
"(SELECT u.id from uum_t_user as u where u.username = #{username})" +
")") List<UUMUserRole> selectUserRolesByName(@Param("username")String username); }

3. 写一个 servcie ,使用上述 mapper, 此过程需要用到 第一步创建的 @bean SqlSessionTemplate

@Service
public class UUMService { CustomUUMMapper uumMapper; @Autowired
@Qualifier("uumsqlSessionTemplate")
SqlSessionTemplate sqlUUMSessionTemplate; /**
*
*/
@PostConstruct
public void init() {
sqlUUMSessionTemplate.getConfiguration().addMapper(CustomUUMMapper.class);
uumMapper = sqlUUMSessionTemplate.getMapper(CustomUUMMapper.class);

} /**
*
* @param name
* @return
*/
public List<UUMUserRole> getAllRolesByUserName(String name){
return uumMapper.selectUserRolesByName(name);
}
}

  Done......

@Component
@Mapper
public interface StudentMapper {
@Insert("insert into student(sno,sname,ssex) values(#{sno},#{name},#{sex})")
int add(Student student); @Update("update student set sname=#{name},ssex=#{sex} where sno=#{sno}")
int update(Student student); @Delete("delete from student where sno=#{sno}")
int deleteBysno(String sno); @Select("select * from student where sno=#{sno}")
@Results(id = "student",value= {
@Result(property = "sno", column = "sno", javaType = String.class),
@Result(property = "name", column = "sname", javaType = String.class),
@Result(property = "sex", column = "ssex", javaType = String.class)
})
Student queryStudentBySno(String sno);
}
package com.hq.service.impl;

import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Component; import java.util.ArrayList;
import java.util.List;
import java.util.Map; @Component
public class SqlTemplate {
private MSUtils msUtils = null;
private SqlSession sqlSession = null; /**
* 构造方法,默认缓存MappedStatement
*
* @param sqlSession
*/
public SqlTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSession = sqlSessionTemplate;
this.msUtils = new MSUtils(sqlSession.getConfiguration());
} /**
* 获取List中最多只有一个的数据
*
* @param list List结果
* @param <T> 泛型类型
* @return
*/
private <T> T getOne(List<T> list) {
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
} /**
* 查询返回一个结果,多个结果时抛出异常
*
* @param sql 执行的sql
* @return
*/
public Map<String, Object> selectOne(String sql) {
List<Map<String, Object>> list = selectList(sql);
return getOne(list);
} /**
* 查询返回一个结果,多个结果时抛出异常
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public Map<String, Object> selectOne(String sql, Object value) {
List<Map<String, Object>> list = selectList(sql, value);
return getOne(list);
} /**
* 查询返回一个结果,多个结果时抛出异常
*
* @param sql 执行的sql
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> T selectOne(String sql, Class<T> resultType) {
List<T> list = selectList(sql, resultType);
return getOne(list);
} /**
* 查询返回一个结果,多个结果时抛出异常
*
* @param sql 执行的sql
* @param value 参数
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> T selectOne(String sql, Object value, Class<T> resultType) {
List<T> list = selectList(sql, value, resultType);
return getOne(list);
} /**
* 查询返回List<Map<String, Object>>
*
* @param sql 执行的sql
* @return
*/
public List<Map<String, Object>> selectList(String sql) {
String msId = msUtils.select(sql);
return sqlSession.selectList(msId);
} /**
* 查询返回List<Map<String, Object>>
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public List<Map<String, Object>> selectList(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.selectDynamic(sql, parameterType);
return sqlSession.selectList(msId, value);
} /**
* 查询返回指定的结果类型
*
* @param sql 执行的sql
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> List<T> selectList(String sql, Class<T> resultType) {
String msId;
if (resultType == null) {
msId = msUtils.select(sql);
} else {
msId = msUtils.select(sql, resultType);
}
return sqlSession.selectList(msId);
} /**
* 查询返回指定的结果类型
*
* @param sql 执行的sql
* @param value 参数
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> List<T> selectList(String sql, Object value, Class<T> resultType) {
String msId;
Class<?> parameterType = value != null ? value.getClass() : null;
if (resultType == null) {
msId = msUtils.selectDynamic(sql, parameterType);
} else {
msId = msUtils.selectDynamic(sql, parameterType, resultType);
}
return sqlSession.selectList(msId, value);
} /**
* 插入数据
*
* @param sql 执行的sql
* @return
*/
public int insert(String sql) {
String msId = msUtils.insert(sql);
return sqlSession.insert(msId);
} /**
* 插入数据
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public int insert(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.insertDynamic(sql, parameterType);
return sqlSession.insert(msId, value);
} /**
* 更新数据
*
* @param sql 执行的sql
* @return
*/
public int update(String sql) {
String msId = msUtils.update(sql);
return sqlSession.update(msId);
} /**
* 更新数据
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public int update(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.updateDynamic(sql, parameterType);
return sqlSession.update(msId, value);
} /**
* 删除数据
*
* @param sql 执行的sql
* @return
*/
public int delete(String sql) {
String msId = msUtils.delete(sql);
return sqlSession.delete(msId);
} /**
* 删除数据
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public int delete(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.deleteDynamic(sql, parameterType);
return sqlSession.delete(msId, value);
} private class MSUtils {
private Configuration configuration;
private LanguageDriver languageDriver; private MSUtils(Configuration configuration) {
this.configuration = configuration;
languageDriver = configuration.getDefaultScriptingLanguageInstance();
} /**
* 创建MSID
*
* @param sql 执行的sql
* @param sql 执行的sqlCommandType
* @return
*/
private String newMsId(String sql, SqlCommandType sqlCommandType) {
StringBuilder msIdBuilder = new StringBuilder(sqlCommandType.toString());
msIdBuilder.append(".").append(sql.hashCode());
return msIdBuilder.toString();
} /**
* 是否已经存在该ID
*
* @param msId
* @return
*/
private boolean hasMappedStatement(String msId) {
return configuration.hasStatement(msId, false);
} /**
* 创建一个查询的MS
*
* @param msId
* @param sqlSource 执行的sqlSource
* @param resultType 返回的结果类型
*/
private void newSelectMappedStatement(String msId, SqlSource sqlSource, final Class<?> resultType) {
MappedStatement ms = new MappedStatement.Builder(configuration, msId, sqlSource, SqlCommandType.SELECT)
.resultMaps(new ArrayList<ResultMap>() {
{
add(new ResultMap.Builder(configuration, "defaultResultMap", resultType, new ArrayList<ResultMapping>(0)).build());
}
})
.build();
//缓存
configuration.addMappedStatement(ms);
} /**
* 创建一个简单的MS
*
* @param msId
* @param sqlSource 执行的sqlSource
* @param sqlCommandType 执行的sqlCommandType
*/
private void newUpdateMappedStatement(String msId, SqlSource sqlSource, SqlCommandType sqlCommandType) {
MappedStatement ms = new MappedStatement.Builder(configuration, msId, sqlSource, sqlCommandType)
.resultMaps(new ArrayList<ResultMap>() {
{
add(new ResultMap.Builder(configuration, "defaultResultMap", int.class, new ArrayList<ResultMapping>(0)).build());
}
})
.build();
//缓存
configuration.addMappedStatement(ms);
} private String select(String sql) {
String msId = newMsId(sql, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newSelectMappedStatement(msId, sqlSource, Map.class);
return msId;
} private String selectDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newSelectMappedStatement(msId, sqlSource, Map.class);
return msId;
} private String select(String sql, Class<?> resultType) {
String msId = newMsId(resultType + sql, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newSelectMappedStatement(msId, sqlSource, resultType);
return msId;
} private String selectDynamic(String sql, Class<?> parameterType, Class<?> resultType) {
String msId = newMsId(resultType + sql + parameterType, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newSelectMappedStatement(msId, sqlSource, resultType);
return msId;
} private String insert(String sql) {
String msId = newMsId(sql, SqlCommandType.INSERT);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.INSERT);
return msId;
} private String insertDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.INSERT);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.INSERT);
return msId;
} private String update(String sql) {
String msId = newMsId(sql, SqlCommandType.UPDATE);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.UPDATE);
return msId;
} private String updateDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.UPDATE);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.UPDATE);
return msId;
} private String delete(String sql) {
String msId = newMsId(sql, SqlCommandType.DELETE);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.DELETE);
return msId;
} private String deleteDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.DELETE);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.DELETE);
return msId;
}
}
}

  

Mybatis 的多个数据源的更多相关文章

  1. spring+mybatis管理多个数据源(非分布式事务)

    本文通过一个demo,介绍如何使用spring+mybatis管理多个数据源,注意,本文的事务管理并非之前博文介绍的分布式事务. 这个demo将使用两个事务管理器分别管理两个数据源.对于每一个独立的事 ...

  2. spring集成mybatis配置多个数据源,通过aop自动切换

    spring集成mybatis,配置多个数据源并自动切换. spring-mybatis.xml如下: <?xml version="1.0" encoding=" ...

  3. Spring Boot 中使用 MyBatis 整合 Druid 多数据源

    2017 年 10 月 20 日   Spring Boot 中使用 MyBatis 整合 Druid 多数据源 本文将讲述 spring boot + mybatis + druid 多数据源配置方 ...

  4. 【Mybatis】MyBatis之配置自定义数据源(十一)

    本例是在[Mybatis]MyBatis之配置多数据源(十)的基础上进行拓展,查看本例请先学习第十章 实现原理 1.扩展Spring的AbstractRoutingDataSource抽象类(该类充当 ...

  5. myBatis源码解析-数据源篇(3)

    前言:我们使用mybatis时,关于数据源的配置多使用如c3p0,druid等第三方的数据源.其实mybatis内置了数据源的实现,提供了连接数据库,池的功能.在分析了缓存和日志包的源码后,接下来分析 ...

  6. Spring Boot 入门系列(二十三)整合Mybatis,实现多数据源配置!

    d之前介绍了Spring Boot 整合mybatis 使用注解方式配置的方式实现增删改查以及一些复杂自定义的sql 语句 .想必大家对spring boot 项目中,如何使用mybatis 有了一定 ...

  7. 使用Spring Profile和Mybatis进行多个数据源(H2和Mysql)的切换

    最近在做WebMagic的后台,遇到一个问题:后台用到了数据库,本来理想情况下是用Mysql,但是为了做到开箱即用,也整合了一个嵌入式 数据库H2.这里面就有个问题了,如何用一套代码,提供对Mysql ...

  8. Spring Boot 整合 Mybatis 实现 Druid 多数据源详解

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “清醒时做事,糊涂时跑步,大怒时睡觉,独处时思考” 本文提纲一.多数据源的应用场景二.运行 sp ...

  9. mybatis配置多个数据源事务(Transaction)处理

    当mybatis配置文件中只有一个数据源的时候,按照正常的事务注解形式@Transaction是没有问题的,但是当配置文件中有多个数据源的时候发现事务不起作用了,怎么解决这个问题呢?看下面的案例:

  10. 2019-04-09 SpringBoot+Druid+MyBatis+Atomikos 的多数据源配置

    前面部分是网上找的,我按照网上写的把自己搭建的过程展示一次 1.引入依赖 目前项目本来使用到了Mybatis plus(在自己的Mapper接口中继承BaseMapper获得基本的CRUD,而不需要增 ...

随机推荐

  1. 22.Container With Most Water(能装最多水的容器)

    Level:   Medium 题目描述: Given n non-negative integers a1, a2, ..., an , where each represents a point ...

  2. OEL6.8安装虚拟带库模拟器

    最近在虚拟机下搭建了一个OSB备份环境,其中使用到了虚拟带库,以下是虚拟带库的配置过程,简要记录之. 1.下载虚拟带库的源码(mhvtl-2016-03-10.tgz). 2.解压缩源码. # cd ...

  3. 获取一个表中的字段总数(mysql) Navicat如何导出Excel格式表结构 获取某个库中的一个表中的所有字段和数据类型

    如何获取一个表中的字段总数 1.function show columns from 表明: 结果 : 2.functiuon select count(*) from INFORMATION_SCH ...

  4. paraview显示指定时间段的时均图(两种方法)

    方法一: 首先计算以后会得到每个时刻的网格数据,如下图: 但是我们只想要比如最后2s的数据,如果直接导入,paraview会把从0s时刻的数据全部加载,做时均图的时候也就是对整个时间段做时均,不是我们 ...

  5. ABP项目后台初始化数据库

    设置host为启动项,并修改连接字符串 在程序包管理控制台中,默认项目选中EFCore 执行Update-Database命令

  6. Joi图标

    刚开始浏览API的时候,旁边这个图片还真没明白是啥意思.现在才明白过来:),检测工具嘛,哈哈.

  7. Git merge 和 rebase 进一步比较

    但是 假如 我不想看到 分支转折点呢 合并的分支始终会存在一个交叉点 Microsoft Windows [版本 10.0.17134.345] (c) Microsoft Corporation.保 ...

  8. jdk8涉及到的接口、类及方法

    bi是binary的简写,二元的,表示两个参数 unary,一元的,表示一个参数 1.函数式接口Supplier T get(),不接收参数,有返回值 IntSupplier,int getAsInt ...

  9. Python 中的反射和自省

    本文主要介绍Python中的反射和自省,以及该机制的简单应用 熟悉Java的程序员,一定经常和Class.forName打交道.即使不是经常亲自调用这个方法,但是在很多框架中(spring,eclip ...

  10. Android:Sqlitedatabase学习小结

    今天刚刚学习完Sqlite数据库的基础知识,随即把学到的东西记录下来,以便随后查阅,以下是自己对Sqlite数据库的小结:1.Sqlite简介       Sqlite是一款轻型的数据库,它包含在一个 ...