1、在pom文件中添加mybatis与jsqlparser的相关依赖
com.github.jsqlparser
jsqlparser
1.0
2、编写一个拦截器并实现ibatis的Interceptor
@Intercepts({ @Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class,Integer.class }) })
public class DataScopeInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler handler = (StatementHandler)invocation.getTarget();
//由于mappedStatement中有我们需要的方法id,但却是protected的,所以要通过反射获取
MetaObject statementHandler = SystemMetaObject.forObject(handler);
MappedStatement mappedStatement = (MappedStatement) statementHandler.getValue("delegate.mappedStatement");
//获取sql
BoundSql boundSql = handler.getBoundSql();
String sql = boundSql.getSql();
//获取方法id
String id = mappedStatement.getId();
//获得方法类型 (如select,update)
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
if ("SELECT".equalsIgnoreCase(sqlCommandType.toString())) {
//增强sql代码块 这里可通过判断用户权限为不通类型的用户拼接不同的sql
sql += " where id = '1'";
//将增强后的sql放回
statementHandler.setValue("delegate.boundSql.sql",sql);
}
return invocation.proceed();
}
@Override
public Object plugin(Object o) {
//生成代理对象
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
}
3、由于springboot对ibatis拦截器不支持自动加载,这里还需依赖mybatis的配置文件
4、在yum文件中进行加载即可
mybatis:
config-location: classpath:mybatis.xml