动态sql

以下是使用 MyBatis-Plus 实现这一逻辑的优化代码:

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

// ...

public List<YourEntity> getFilteredData(Map<Boolean, List<Long>> partitionedSubIds) {
    List<Long> enabledSubIds = partitionedSubIds.getOrDefault(true, Collections.emptyList());
    List<Long> disabledSubIds = partitionedSubIds.getOrDefault(false, Collections.emptyList());
    
    LambdaQueryWrapper<YourEntity> queryWrapper = Wrappers.lambdaQuery();
    
    // 当两个列表都为空时,查询所有数据(不添加 sub_id 和 enable 条件)
    if (!enabledSubIds.isEmpty() || !disabledSubIds.isEmpty()) {
        queryWrapper.and(wrapper -> {
            // 添加 enable = 1 且 sub_id IN (enabledSubIds) 的条件
            if (!enabledSubIds.isEmpty()) {
                wrapper.and(enabledWrapper -> 
                    enabledWrapper.eq(YourEntity::getEnable, 1)
                                  .in(YourEntity::getSubId, enabledSubIds)
                );
            }
            
            // 添加 OR 条件
            if (!enabledSubIds.isEmpty() && !disabledSubIds.isEmpty()) {
                wrapper.or();
            }
            
            // 添加 enable = 0 且 sub_id IN (disabledSubIds) 的条件
            if (!disabledSubIds.isEmpty()) {
                wrapper.and(disabledWrapper -> 
                    disabledWrapper.eq(YourEntity::getEnable, 0)
                                   .in(YourEntity::getSubId, disabledSubIds)
                );
            }
        });
    }
    
    // 添加公共条件和排序
    queryWrapper.eq(YourEntity::getIsDel, 0) // 假设 is_del = 0 表示未删除
                .orderByDesc(YourEntity::getCreateTime);
    
    return yourEntityMapper.selectList(queryWrapper);
}

代码说明:

  1. 动态条件构建

    • enabledSubIdsdisabledSubIds 都为空时,不添加 sub_idenable 条件,查询所有数据
    • 使用 and().and().or().and() 结构构建复杂条件,生成的 SQL 类似:
      WHERE is_del = 0 
        AND ((enable = 1 AND sub_id IN (?)) OR (enable = 0 AND sub_id IN (?)))
      ORDER BY create_time DESC
      
  2. 参数处理

    • 自动处理 List<Long> 到 SQL IN 子句的转换
    • 空列表会被忽略,不会生成无效的 IN () 条件
  3. 性能优化

    • 建议添加复合索引:
      CREATE INDEX idx_enable_subid ON your_table (enable, sub_id);
      
    • 当查询全量数据时,会跳过不必要的条件过滤
  4. 使用示例

    // 查询 enable=1 的 sub_id=1,2 和 enable=0 的 sub_id=3,4
    Map<Boolean, List<Long>> partitionedSubIds = new HashMap<>();
    partitionedSubIds.put(true, Arrays.asList(1L, 2L));
    partitionedSubIds.put(false, Arrays.asList(3L, 4L));
    List<YourEntity> result = service.getFilteredData(partitionedSubIds);
    

这个实现兼顾了灵活性和性能,能够根据不同的输入动态调整查询条件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值