阿超
        >
        
mybatis-plus过滤不需要查询的字段
     
    
    
    
    
    
        
仁义忠信,乐善不倦,此天爵也 。一一孟子
之前写过过滤出需要查询的字段,也简单介绍了下Mybatis-Plus的select函数
今天写了个小函数,可以直接传入不需要查询出来的字段
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | 
 
 
 
 
 
 
 
 @SafeVarargs
 public static <T> LambdaQueryWrapper<T> filterProperties(LambdaQueryWrapper<T> wrapper, SFunction<T, Serializable>... functions) {
 return Optional.ofNullable(functions).filter(ArrayUtils::isNotEmpty).map(array -> Arrays.stream(array).map(LambdaUtils::resolve).map(SerializedLambda::getImplMethodName).map(PropertyNamer::methodToProperty).collect(Collectors.toList())).map(properties -> wrapper.select(i -> !properties.contains(i.getProperty()))).orElse(wrapper);
 }
 
 | 
使用方式:
| 12
 
 | LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>(new Product());MybatisPlusUtils.filterProperties(wrapper, Product::getDetail, Product::getParams)
 
 | 
或者直接
| 1
 | LambdaQueryWrapper<Product> lambdaQueryWrapper = MybatisPlusUtils.filterProperties(new LambdaQueryWrapper<>(new Product()), Product::getDetail, Product::getParams);
 | 
注意,LambdaQueryWrapper需要使用带实体的有参构造

当然也可以不用,我们只需要稍作修改:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 
 | 
 
 
 
 
 
 
 
 @SafeVarargs
 @SuppressWarnings("unchecked")
 public static <T> LambdaQueryWrapper<T> filterProperties(LambdaQueryWrapper<T> wrapper, SFunction<T, Serializable>... functions) {
 Set<SerializedLambda> lambdas = Optional.ofNullable(functions).filter(ArrayUtils::isNotEmpty).map(array -> Arrays.stream(array).map(LambdaUtils::resolve).collect(Collectors.toSet())).orElseGet(Collections::emptySet);
 Set<String> properties = lambdas.stream().map(SerializedLambda::getImplMethodName).map(PropertyNamer::methodToProperty).collect(Collectors.toSet());
 lambdas.stream().findAny().ifPresent(lam -> wrapper.select((Class<T>) lam.getImplClass(), i -> !properties.contains(i.getProperty())));
 return wrapper;
 }
 
 | 
这样就可以不用使用带实体的有参构造啦