以下是使用 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);
}
代码说明:
-
动态条件构建:
- 当
enabledSubIds
和disabledSubIds
都为空时,不添加sub_id
和enable
条件,查询所有数据 - 使用
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
- 当
-
参数处理:
- 自动处理
List<Long>
到 SQLIN
子句的转换 - 空列表会被忽略,不会生成无效的
IN ()
条件
- 自动处理
-
性能优化:
- 建议添加复合索引:
CREATE INDEX idx_enable_subid ON your_table (enable, sub_id);
- 当查询全量数据时,会跳过不必要的条件过滤
- 建议添加复合索引:
-
使用示例:
// 查询 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);
这个实现兼顾了灵活性和性能,能够根据不同的输入动态调整查询条件。