查询需求
多个and组合成一个组合条件,多个组合条件之间用或连接(or).
例如:
SELECT basic_rule_snapshot_id FROM alarm_info WHERE (
status = ? AND (
(basic_rule_snapshot_id = ? AND industry_device_id = ?) OR
(basic_rule_snapshot_id = ? AND industry_device_id = ?) OR
(basic_rule_snapshot_id = ? AND industry_device_id = ?)
)
)
lambdaQuery
wrapper.select(AlarmInfo::getBasicRuleSnapshotId).eq(AlarmInfo::getStatus, AlarmStateEnum.RUNNING.getState());
wrapper.and(w->{
query.getIndustryDeviceSnapshotList().forEach(item->{
w.and(t->{
t.eq(AlarmInfo::getBasicRuleSnapshotId,item.getBasicRuleSnapshotId())
.eq(AlarmInfo::getIndustryDeviceId,item.getIndustryDeviceId());
w.or();
});
});
});
错误写法
容易出错的地方是or()的位置
List<String> serviceIds = query.getServiceIds();
if (CollUtil.isNotEmpty(serviceIds)) {
wrapper.and(q ->
serviceIds.forEach(serviceId -> {
if (StrUtil.isBlank(serviceId) || !serviceId.contains("@")) {
return;
}
q.and(x->
x.eq(AlarmInfo::getSourceFrom, serviceId.split("@")[0])
.eq(AlarmInfo::getPointLongCode, serviceId.split("@")[1])).or();
//此处or()无用,lambda自行体会。
})
);
}
导致sql的or被and替代。
SELECT basic_rule_snapshot_id FROM alarm_info WHERE (status = ? AND ((basic_rule_snapshot_id = ? AND industry_device_id = ?) AND(basic_rule_snapshot_id = ? AND industry_device_id = ?) AND(basic_rule_snapshot_id = ? AND industry_device_id = ?)))