利用mybatis插件动态切换数据源

本文介绍了如何在Spring Boot项目中创建插件类实现数据源切换,通过注解标记需要切换的数据源实体,并创建配置插件来管理数据源。实例展示了如何使用`ChangeDataSource`注解和`ChangeDataSourceHandler`拦截器来确保在执行特定操作时自动切换数据库。

1.创建插件类

2.注解类,标志该类是否需要切换数据源

3.实体类使用注解标志 

4.创建配置插件类

1.

package com.upmsproj.wp.common.plugin;

import com.upmsproj.wp.common.ChangeDataSource;
import com.upmsproj.wp.common.config.datasource.DynamicDataSourceContextHolder;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Value;

import java.util.Properties;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}

        )
})
public class ChangeDataSourceHandler implements Interceptor {

    @Value("${customer.sysDataBase}")
    private String sysDataBase;

    private Boolean needChangeDataBase(Invocation invocation){
        Object[] args = invocation.getArgs();
        Class<?> entityClass = args[1].getClass(); //实体类对象
        ChangeDataSource declaredAnnotation = entityClass.getDeclaredAnnotation(ChangeDataSource.class);
        return "YES".equals(declaredAnnotation.value());
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if(needChangeDataBase(invocation)){
            DynamicDataSourceContextHolder.setDataSourceRouterKey(sysDataBase);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

2.

package com.upmsproj.wp.common;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ChangeDataSource {
    String value() default "NO" ;
}

3.

package com.upmsproj.wp.basicdata.entity;

import com.upmsproj.wp.common.ChangeDataSource;
import com.upmsproj.wp.common.config.datasource.DataBase;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonProperty;

@ApiModel
@Table(name = "dbo.PMS_MESSAGESET")
@ChangeDataSource("YES")
public class PMS_MESSAGESET {

    @Api
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Listest

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值