【web|Mybatis拦截器实现SAAS平台(动态修改SQL)随笔】首先,自定义拦截器
import com.swzx.risktech.model.User;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;
/**
* author:cs2019/02/28
*///拦截StatementHandler类中参数类型为Statement的 prepare 方法
//即拦截 Statement prepare(Connection var1, Integer var2) 方法
@Component
@Intercepts({@Signature(type = StatementHandler.class,method = "prepare",args = {Connection.class,Integer.class})})
public class SqlInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session=request.getSession();
//获取到原始sql语句
String sql = boundSql.getSql();
String mSql = "";
String strsql = sql.replace(" ","");
User user = (User)session.getAttribute("loginUser");
if(strsql.indexOf("cid=")==-1) {
if (sql.indexOf("where")!=-1){
mSql = sql + " and cid="+user.getCid();
}else{
mSql = sql + " where and cid="+user.getCid();
}
}
//通过反射修改sql语句
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql, mSql);
return invocation.proceed();
}@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}@Override
public void setProperties(Properties properties) {
//此处可以接收到配置文件的property参数
}
}
然后就没有然后了,就是这么简单。
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- mysql|InnoDB数据页结构
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- javaweb|基于Servlet+jsp+mysql开发javaWeb学生成绩管理系统
- JavaScript|JavaScript: BOM对象 和 DOM 对象的增删改查
- Spring注解驱动第十讲--@Autowired使用