背景:
- 项目中需要根据企业分对应的数据库,所以要动态根据企业的标识去操作对应的数据库
思路:
- 用
mybatis plus
动态表名,但是有个缺点就是只会在项目启动是注入bean对象时调用一次,不像拦截器那样每次调用,所以放弃了;(其实简单的根据日期什么的切换数据表,直接用mp的这种实现更加简单)
- 使用
mybatis
的拦截器
Example:
package com.huawen.framework.interceptor;
import cn.hutool.core.util.ObjectUtil;
import com.huawen.common.enums.CompanyEnum;
import com.huawen.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;
@Slf4j
@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class AddDbPrefixInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
log.info("执行intercept方法:{}", invocation.toString());
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String origSql = boundSql.getSql();
log.info("原始SQL: {}", origSql);
String newSql = addDbPrefixBeforeTableName(origSql);
log.info("修改后SQL: {}", newSql);
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql, newSql);
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
private String addDbPrefixBeforeTableName(String sql) {
try {
} catch (Exception e) {
}
return sql;
}
}