@Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); ArrayList<ISqlParser> sqlParserList = new ArrayList<>(); TenantSqlParser tenantSqlParser = new TenantSqlParser(); tenantSqlParser.setTenantHandler(new TenantHandler() { @Override public String getTenantIdColumn() { //获取租户字段名 return "manager_id"; } @Override public Expression getTenantId() { //获取租户 ID 值表达式,只支持单个 ID 值,一般来自session/token等 return new LongValue(1087982257332887553L); } @Override public boolean doTableFilter(String tableName) { //根据表名判断是否忽略拼接多租户条件 //默认都要进行解析并拼接多租户条件 //true:表示忽略,false:需要解析并拼接多租户条件 return false; } }); sqlParserList.add(tenantSqlParser); paginationInterceptor.setSqlParserList(sqlParserList); return paginationInterceptor; }
@Test public void select(){ List<User> list = userMapper.selectList(null); list.forEach(System.out::println); }
可以看到测试虽然是查询全部,但是添加了条件:manager_id = 1087982257332887553
这种方式可以过滤MP自带的方法,也可以过滤我们自己定义在xml里的方法
@Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); ArrayList<ISqlParser> sqlParserList = new ArrayList<>(); TenantSqlParser tenantSqlParser = new TenantSqlParser(); tenantSqlParser.setTenantHandler(new TenantHandler() { @Override public String getTenantIdColumn() { //获取租户字段名 return "manager_id"; } @Override public Expression getTenantId() { //获取租户 ID 值表达式,只支持单个 ID 值,一般来自session/token等 return new LongValue(1087982257332887553L); } @Override public boolean doTableFilter(String tableName) { //根据表名判断是否忽略拼接多租户条件 //默认都要进行解析并拼接多租户条件 //true:表示忽略,false:需要解析并拼接多租户条件 return false; } }); sqlParserList.add(tenantSqlParser); paginationInterceptor.setSqlParserList(sqlParserList); //设置哪些SQL不拼接多租户条件 paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() { //true:表示忽略,false:需要解析并拼接多租户条件 @Override public boolean doFilter(MetaObject metaObject) { MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject); if ("com.mp.dao.UserMapper.selectList".equals(ms.getId())) { return true; } return false; } }); return paginationInterceptor; }
使用@SqlParser(filter = true)来过滤
public interface UserMapper extends BaseMapper<User> { @SqlParser(filter = true) List<User> selectAll(@Param(Constants.WRAPPER) Wrapper<User> queryWrapper); }
注意:低版本MP需要在配置文件中设置:mybatis-plus.global-config.sql-parser-cache=true
原文:https://www.cnblogs.com/jwen1994/p/14539333.html