Mybatis Plus怎么配置双数据库驱动连接数据库
发表于:2025-11-12 作者:千家信息网编辑
千家信息网最后更新 2025年11月12日,本文小编为大家详细介绍"Mybatis Plus怎么配置双数据库驱动连接数据库",内容详细,步骤清晰,细节处理妥当,希望这篇"Mybatis Plus怎么配置双数据库驱动连接数据库"文章能帮助大家解决
千家信息网最后更新 2025年11月12日Mybatis Plus怎么配置双数据库驱动连接数据库
本文小编为大家详细介绍"Mybatis Plus怎么配置双数据库驱动连接数据库",内容详细,步骤清晰,细节处理妥当,希望这篇"Mybatis Plus怎么配置双数据库驱动连接数据库"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
具体实现
1、在pom.xml中添加如下依赖:
1.8 1.18.2 3.2.0 1.1.9 UTF-8 UTF-8 org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime org.postgresql postgresql runtime com.baomidou mybatis-plus-boot-starter ${mybatis-plus.version} com.baomidou mybatis-plus ${mybatis-plus.version} org.projectlombok lombok ${lombok.version} com.alibaba druid-spring-boot-starter ${druid.version} org.springframework.boot spring-boot-starter-aop
2、在yml配置文件中添加如下配置:
server: port: 8080 spring: application: name: xxxx datasource: druid: # mysql数据源配置 db1: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: ${username} password: ${password} initial-size: 5 min-idle: 5 max-active: 50 # postgresql 数据源配置 db2: driver-class-name: org.postgresql.Driver url: jdbc:postgresql://127.0.0.1:5432/db2?useUnicode=true&characterEncoding=utf-8 username: ${username} password: ${password} initial-size: 5 min-idle: 5 max-active: 50 # mybatis-plus配置mybatis-plus: type-aliases-package: com.dms.gateway.api.entity mapper-locations: classpath:/mapper/*Mapper.xml global-config: db-config: id-type: auto field-strategy: not_empty logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true cache-enabled: false call-setters-on-nulls: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl3、新建DataSourceEnum枚举类,如下:
public enum DataSourceEnum { DB1("db1"), DB2("db2"); private String value; DataSourceEnum(String value){this.value=value;} public String getValue() { return value; }}4、新建DataSourceContextHolder类,如下:
public class DataSourceContextHolder { // 默认数据源 public static final String DEFAULT_DS = DataSourceEnum.DB1.getValue(); private static final ThreadLocal contextHolder = new InheritableThreadLocal<>(); /** * 设置数据源 * @param db */ public static void setDataSource(String db){ contextHolder.set(db); } /** * 取得当前数据源 * @return */ public static String getDataSource(){ return contextHolder.get(); } /** * 清除上下文数据 */ public static void clear(){ contextHolder.remove(); }} 5、新建MultipleDataSource类,如下:
public class MultipleDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSource(); }}6、新建DataSource注解,如下:
@Target({ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface DataSource { DataSourceEnum value() default DataSourceEnum.DB1;}7、新建面向类和方法级别的切面,如下:
@Component@Slf4j@Aspect@Order(-6)public class DataSourceClassAspect { @Before("@within(dataSource)") public void doBefore(JoinPoint point, DataSource dataSource){ log.info("切换到数据源[{}]", dataSource.value().getValue()); DataSourceContextHolder.setDataSource(dataSource.value().getValue()); } @After("@within(dataSource)") public void doAfter(JoinPoint point, DataSource dataSource){ log.info("回收数据源[{}]", dataSource.value().getValue()); DataSourceContextHolder.clear(); }}@Component@Slf4j@Aspect@Order(-5)public class DataSourceMethodAspect { @Before("@annotation(dataSource)") public void doBefore(JoinPoint point, DataSource dataSource){ log.info("切换到数据源[{}]", dataSource.value().getValue()); DataSourceContextHolder.setDataSource(dataSource.value().getValue()); } @After("@annotation(dataSource)") public void doAfter(JoinPoint point, DataSource dataSource){ log.info("回收数据源[{}]", dataSource.value().getValue()); DataSourceContextHolder.clear(); }}8、新建多数据源配置类,如下:
@Configuration@MapperScan("com.dms.gateway.api.mapper")public class MybatisPlusConfig { /* * 分页插件,自动识别数据库类型 * 多租户,请参考官网【插件扩展】 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; } @Bean(name = "db1") @ConfigurationProperties(prefix = "spring.datasource.druid.db1" ) public DataSource db1() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "db2") @ConfigurationProperties(prefix = "spring.datasource.druid.db2" ) public DataSource db2() { return DruidDataSourceBuilder.create().build(); } /** * 动态数据源配置 * @return */ @Bean @Primary public DataSource multipleDataSource(@Qualifier("db1") DataSource db1, @Qualifier("db2") DataSource db2) { MultipleDataSource multipleDataSource = new MultipleDataSource(); Map< Object, Object > targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceEnum.DB1.getValue(), db1); targetDataSources.put(DataSourceEnum.DB2.getValue(), db2); //添加数据源 multipleDataSource.setTargetDataSources(targetDataSources); //设置默认数据源 multipleDataSource.setDefaultTargetDataSource(db1); return multipleDataSource; } @Bean("sqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean(); sqlSessionFactory.setDataSource(multipleDataSource(db1(),db2())); MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setJdbcTypeForNull(JdbcType.NULL); configuration.setMapUnderscoreToCamelCase(true); configuration.setCacheEnabled(false); sqlSessionFactory.setConfiguration(configuration); //添加分页功能 sqlSessionFactory.setPlugins(paginationInterceptor()); return sqlSessionFactory.getObject(); }}接下来需要具体的业务逻辑,在service层的类或者方法上面添加@DataSource注解来指定该业务需要用到的数据源,如下:
@Service@DataSource(DataSourceEnum.DB2)public class GatewayLogService { @Autowired private GatewayLogMapper mapper; @Override public Result> pageList(GatewayLogDTO gatewayLogDTO) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getPath()), GatewayLog::getPath, gatewayLogDTO.getPath()); wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getSourceServer()), GatewayLog::getSourceServer, gatewayLogDTO.getSourceServer()); wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getTargetServer()), GatewayLog::getTargetServer, gatewayLogDTO.getTargetServer()); wrapper.eq(StringUtils.isNotEmpty(gatewayLogDTO.getMethod()), GatewayLog::getMethod, gatewayLogDTO.getMethod()); wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getRequestBody()), GatewayLog::getRequestBody, gatewayLogDTO.getRequestBody()); wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getResponse()), GatewayLog::getResponse, gatewayLogDTO.getResponse()); wrapper.orderByDesc(GatewayLog::getId); IPage page = new Page<>(gatewayLogDTO.getPageNo(), gatewayLogDTO.getPageSize()); return Result.success(mapper.selectPage(page, wrapper)); } } 启动服务,调用相关的接口,我们会在控制台看到如下信息:

说明数据源切换成功!!!
读到这里,这篇"Mybatis Plus怎么配置双数据库驱动连接数据库"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。
数据
数据源
配置
数据库
驱动
文章
切换
业务
内容
插件
方法
注解
UTF-8
妥当
成功
接下来
上下
上下文
信息
切面
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
网吧pubg怎么换服务器
互联网科技巨头的垄断行为
网吧服务器主机怎么安装
湖南智慧党建软件开发软件
达内学软件开发培训课程
具前景的数据库运维管理
帝国神话创建服务器多少内存
凯里黄河服务器供应商
怎样修改数据库用户名
没有数据库能进入后台吗
dw配置服务器
文献数据库购买
nat云服务器怎么搭建网站
关于科技与互联网的文案
搭建小型网络首选的网络技术是
朔州拼接屏触摸软件开发公司
ios软件开发架构
腾讯云服务器服务器管理器
学校与网络技术公司签订合同
c 代码接入数据库方法
阿里云服务器变慢
凯里黄河服务器供应商
手机原神怎么切换服务器
c语言连接数据库实现登录
新媒体网络安全
计算机网络技术专科求职意向
厂家软件开发优化建站
csgo连接显示香港服务器
网络安全手抄报没有颜色
网络安全审查办法审查范围