前言
这几天在使用的mybatis-plus的时候,在遇见复杂业务的时候遇见的一些租户过滤问题,面对多表关联查询的时候、自定义sql的时候,或者说一对多的时候,其中一个查询等功能过滤过滤租户的解决方案。
在一个缓存命中率不高的场景中,分页很多时候不能依赖主数据分页查询再遍历查询的方式来组装数据的时候,就会遇见自定义sql 或者是一对多查询。这个时候如果用mybatis-plus的多租户就会很有问题。
自定义sql分页查询方法:
Mapper.xml
<select id="getPageUser" resultMap="userResult">
select * from user ${ew.customSqlSegment}
</select>
这里的SQL很简单,根据自己的业务变动sql。${ew.customSqlSegment} 很多人不了解这个哈,就是:Wrapper<Material> queryWrapper 转化后的sql。还不明白的话,继续看...
Mapper.java
@Mapper
public interface UserMapper extends BaseMapper<User> {
List<User> getPageUser(@Param(Constants.WRAPPER) Wrapper<Material> queryWrapper);
}
看清楚哦,这里返回的是一个list集合。${ew.customSqlSegment} 就是指的这的queryWrapper,ew就是Constants.WRAPPER的值。
ServiceImpl.java
@Override
public PageInfo<User> getPageUser(PageParam<UserQueryParam> param, Wrapper<User> queryWrapper) {
// TODO Auto-generated method stub
PageHelper.startPage(param.getCurrent(), param.getPageSize());
List<User> list = baseMapper.getPageUser(queryWrapper);
PageInfo<User> pageInfo = new PageInfo<User>(list);
return pageInfo;
}
PageParam 就是组装了,当前页码与页行数,UserQueryParam 是查询条件:用于组装在queryWrapper中。
Service.java、Controller.java我就直接省了....
多租户面临的情况:
mybatis-plus 多住户配置:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.s