一、简介
MybatisPlus中引用多数据库时,传统的配置就失效了,需要单独写配置来实现,下面就说一下具体应该如何操作
二、引入MybatisPlus多数据源配置
还是先看一下我的项目结构,Model是单独的模块,请自行创建
1、创建一个Maven项目,修改pom.xml文件增加对spring boot、mybatis plus、druid、mysql connector的引用
org.springframework.boot
spring-boot-dependencies
2.0.3.RELEASE
pom
import
org.springframework.boot
spring-boot-starter-web
com.alibaba
druid-spring-boot-starter
1.1.10
mysql
mysql-connector-java
5.1.9
com.baomidou
mybatis-plus-boot-starter
2.3
2、创建resources文件夹,并创建application.yml文件增加以下配置,此处不需要写mybatis plus的配置了,因为多数据源时这里的mybatis plus会失效,具体原因还没找到
#设置提供的服务名
spring:
application:
name: javademo-tyh-service-hotel#配置数据库
datasource:
type: com.alibaba.druid.pool.DruidDataSource
db1:
url: jdbc:mysql://10.11.12.237:3306/db_test?useUnicode=true&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
db2:
url: jdbc:mysql://10.11.12.237:3306/tyh_test?useUnicode=true&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver#设置自己启动的端口
server:
port:12000
3、在resources文件夹下创建mapper文件夹,在其内部创建两个数据库的两张表的mapper.xml文件,分别编写一个自定义方法
BaseInfoMapper.xml
select count(*) from base_info;
UserInfoMapper.xml
select count(*) from user_info;
4、打开main方法所在的类并修改为如下代码
importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("javademo.tyh.service.hotel.mapper")//标记扫描的mapper位置
public classAppServiceHotel
{public static voidmain( String[] args )
{
SpringApplication.run(AppServiceHotel.class, args);
}
}
5、创建config文件夹,存放mybatis plus的相关配置,此内部的类很多都摘自官网,是按照他的方式进行实现的
创建枚举DBTypeEnum
/*** 多数据源枚举*/
public enumDBTypeEnum {
db1("db1"), db2("db2");privateString value;
DBTypeEnum(String value) {this.value =value;
}publicString getValue() {returnvalue;
}
}
创建数据源操作类DbContextHolder
public classDbContextHolder {private static final ThreadLocal contextHolder = new ThreadLocal<>();/*** 设置数据源
*@paramdbTypeEnum*/
public static voidsetDbType(DBTypeEnum dbTypeEnum) {
contextHolder.set(dbTypeEnum.getValue());
}/*** 取得当前数据源
*@return
*/
public staticString getDbType() {return(String) contextHolder.get();
}/*** 清除上下文数据*/
public static voidclearDbType() {
contextHolder.remove();
}
}
创建spring的DataSource抽象类 DynamicDataSource
importorg.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;/** 扩展Spring的AbstractRoutingDataSource抽象类,实现动态数据源。
* AbstractRoutingDataSource中的抽象方法determineCurrentLookupKey是实现数据源的route的核心,
* 这里对该方法进行Override。 【上下文DbContextHolder为一线程安全的ThreadLocal】*/
public class DynamicDataSource extendsAbstractRoutingDataSource {/*** 取得当前使用哪个数据源
*@return
*/@OverrideprotectedObject determineCurrentLookupKey(){returnDbContextHolder.getDbType();
}
}
创建MybatisPlusConfig配置类
importcom.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;importcom.baomidou.mybatisplus.MybatisConfiguration;importcom.baomidou.mybatisplus.entity.GlobalConfiguration;importcom.baomidou.mybatisplus.mapper.LogicSqlInjector;importcom.baomidou.mybatisplus.plugins.PaginationInterceptor;importcom.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;importorg.apache.ibatis.plugin.Interceptor;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.type.JdbcType;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;importjavax.sql.DataSource;importjava.util.HashMap;importjava.util.Map;/*** MybatisPlus配置*/@Configurationpublic classMybatisPlusConfig {//分页拦截器
@BeanpublicPaginationInterceptor paginationInterceptor() {return newPaginationInterceptor();
}//定义db1
@Bean(name = "db1")
@ConfigurationProperties(prefix= "spring.datasource.db1")//与配置文件中的层次结构相同
publicDataSource db1() {returnDruidDataSourceBuilder.create().build();
}//定义db2
@Bean(name = "db2")
@ConfigurationProperties(prefix= "spring.datasource.db2")//与配置文件中的层次结构相同
publicDataSource db2() {returnDruidDataSourceBuilder.create().build();
}/*** 动态数据源配置
*@return
*/@Bean
@Primarypublic DataSource multipleDataSource(@Qualifier("db1") DataSource db1, @Qualifier("db2") DataSource db2) {
DynamicDataSource dynamicDataSource= newDynamicDataSource();
Map targetDataSources = new HashMap<>();
targetDataSources.put(DBTypeEnum.db1.getValue(), db1);
targetDataSources.put(DBTypeEnum.db2.getValue(), db2);
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.setDefaultTargetDataSource(db1);returndynamicDataSource;
}
@Bean("sqlSessionFactory")public SqlSessionFactory sqlSessionFactory() throwsException {//***导入MybatisSqlSession配置***
MybatisSqlSessionFactoryBean sqlSessionFactory = newMybatisSqlSessionFactoryBean();//指明数据源
sqlSessionFactory.setDataSource(multipleDataSource(db1(), db2()));//指明mapper.xml位置(配置文件中指明的xml位置会失效用此方式代替,具体原因未知)
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/**Mapper.xml"));//指明实体扫描(多个package用逗号或者分号分隔)
sqlSessionFactory.setTypeAliasesPackage("javademo.tyh.model.base;javademo.tyh.model.hotel");//***导入Mybatis配置***
MybatisConfiguration configuration = newMybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
sqlSessionFactory.setPlugins(newInterceptor[]{paginationInterceptor()});//***导入全局配置***
sqlSessionFactory.setGlobalConfig(globalConfiguration());returnsqlSessionFactory.getObject();
}/*** 在代码中配置MybatisPlus替换掉application.yml中的配置
*@return
*/@BeanpublicGlobalConfiguration globalConfiguration() {
GlobalConfiguration conf= new GlobalConfiguration(newLogicSqlInjector());//主键类型 0:数据库ID自增, 1:用户输入ID,2:全局唯一ID (数字类型唯一ID), 3:全局唯一ID UUID
conf.setIdType(0);//字段策略(拼接sql时用于判断属性值是否拼接) 0:忽略判断,1:非NULL判断,2:非空判断
conf.setFieldStrategy(2);//驼峰下划线转换含查询column及返回column(column下划线命名create_time,返回java实体是驼峰命名createTime,开启后自动转换否则保留原样)
conf.setDbColumnUnderline(true);//是否动态刷新mapper
conf.setRefresh(true);returnconf;
}
}
6、创建mapper文件夹用于存放于xml对应的mapper接口
BaseInfoMapper
importcom.baomidou.mybatisplus.mapper.BaseMapper;importjavademo.tyh.model.hotel.BaseInfoModel;importorg.springframework.stereotype.Component;
@Componentpublic interface BaseInfoMapper extends BaseMapper{//自定义方法
intlistCount();
}
UserInfoMapper
importcom.baomidou.mybatisplus.mapper.BaseMapper;importjavademo.tyh.model.hotel.UserInfoModel;importorg.springframework.stereotype.Component;
@Componentpublic interface UserInfoMapper extends BaseMapper{//自定义方法
intlistCount();
}
7、创建service文件夹用于存放业务逻辑类
importjavademo.tyh.model.hotel.BaseInfoModel;importjavademo.tyh.model.hotel.UserInfoModel;importjavademo.tyh.service.hotel.config.DBTypeEnum;importjavademo.tyh.service.hotel.config.DbContextHolder;importjavademo.tyh.service.hotel.mapper.BaseInfoMapper;importjavademo.tyh.service.hotel.mapper.UserInfoMapper;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;
@Servicepublic classHotelService {
@Autowired
BaseInfoMapper baseMapper;
@Autowired
UserInfoMapper userMapper;public voidtestDynamicDb() {//使用db1
DbContextHolder.setDbType(DBTypeEnum.db1);
BaseInfoModel baseModel= baseMapper.selectById(1);int baseCount =baseMapper.listCount();
System.out.println("db1=" +baseModel.getNickname());//使用db2
DbContextHolder.setDbType(DBTypeEnum.db2);
UserInfoModel userModel= userMapper.selectById(1);int userCount =userMapper.listCount();
System.out.println("db2=" +userModel.getUsername());
}
}
8、创建controller文件夹编写一个controller和action用于测试
importjavademo.tyh.service.hotel.service.HotelService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/hotel")public classHotelController {
@Autowired
HotelService service;
@ResponseBody
@RequestMapping("/test")public voidtest() {
service.testDynamicDb();
}
}
9、创建自己的实体Model,get/set方法自己生成吧
BaseInfoModel
importcom.baomidou.mybatisplus.annotations.TableName;importjava.time.LocalDateTime;
@TableName("base_info")public classBaseInfoModel {private intid;privateString nickname;privateLocalDateTime updateTime;
}
UserInfoModel
importcom.baomidou.mybatisplus.annotations.TableName;importjava.time.LocalDateTime;
@TableName("user_info")public classUserInfoModel {private intid;privateString username;privateString password;private intsex;private intage;privateLocalDateTime createTime;
}
OK,至此Mybatis Plus多数据源配置Demo就完成了,可以运行http://localhost:12000/hotel/test看一下console控制台会得到以下输出,db1和db2就切换成功了