首先,使用Mybatis配置多个数据源需要用到两个工具类:SqlSessionFactory MapperFactory
/**
* 根据mybatis.xml中配置的不同的environment创建对应的SqlSessionFactory
*/
public final class SqlSessionFactory {
private static final Logger logger = LoggerFactory.getLogger(SqlSessionFactory.class);
private static final String CONFIGURATION_PATH = "mybatis/mybatis-config.xml";
private static final Map<String, org.apache.ibatis.session.SqlSessionFactory> SQLSESSIONFACTORYS = new HashMap();
/**
* 根据指定的DataSourceEnvironment获取对应的SqlSessionFactory
*/
public static org.apache.ibatis.session.SqlSessionFactory getSqlSessionFactory(String datasource) {
org.apache.ibatis.session.SqlSessionFactory sqlSessionFactory = SQLSESSIONFACTORYS.get(datasource);
if (!Objects.isNull(sqlSessionFactory))
return sqlSessionFactory;
else {
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(CONFIGURATION_PATH);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, datasource);
logger.info("Get {} SqlSessionFactory successfully.", datasource);
} catch (IOException e) {
logger.warn("Get {} SqlSessionFactory error.", datasource);
logger.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(inputStream);
}
SQLSESSIONFACTORYS.put(datasource, sqlSessionFactory);
return sqlSessionFactory;
}
}
}
/**
* MapperFactory 创建一个Mapper实例 mapper
*/
public final class MapperFactory {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MapperFactory.class);
/**
* 通过datasource 创建一个Mapper 的实现类 mapper
*/
@SuppressWarnings("unchecked")
public static <T&g