业务背景:
A方法构建了一个Example 对象,放入部分初始检索条件,需要循环数据,针对每条数据构建Example ,用之前的检索条件+本次的检索条件,如果直接new一个,将之前的赋值给新的,那么每次循环的时候就会将上次的条件拼上
解决方案:将初始Example的检索条件取出,每次循环的时候构建一个全新的,手动写入之前的检索条件+本次的
if (StrKit.isNotEmpty(empInfoQuery.getTag())) {
String[] array = empInfoQuery.getTag().split(",");
List<String> tagList = Arrays.asList(array);
if (tagList.size() == 1) {
String tagName = tagList.get(0);
example.and().andCondition("FIND_IN_SET('" + tagName + "' , tag)");
empInfoList = listVoRelationByExample(empInfoQuery.getCompanyId(), example, tokenUser.getSiteId());
} else {
// 如果不带标签的检索都查不到人,就没必要检索标签了
List<EmpInfoListVO> empInfoListVOS = listVoRelationByExample(empInfoQuery.getCompanyId(), example, tokenUser.getSiteId());
if (CollectionUtils.isEmpty(empInfoListVOS)) {
return new ArrayList<>();
}
for (String tagName : tagList) {
Example example1 = ExampleKit.copyExample(example, EmpInfoDO.class);
example1.and().andCondition("FIND_IN_SET('" + tagName + "' , tag)");
List<EmpInfoListVO> empInfoListItem = listVoRelationByExample(empInfoQuery.getCompanyId(), example1, tokenUser.getSiteId());
empInfoList.addAll(empInfoListItem);
}
// 去重
empInfoList = empInfoList.stream().distinct().collect(Collectors.toList());
}
}
/**
* 复制example查询条件
*
* @param source 源example
* @param dClass class类
* @return example
*/
public static Example copyExample(Example source, Class<?> dClass) {
Example example = new Example(dClass);
List<Example.Criteria> oredCriteriaList = source.getOredCriteria();
for (Example.Criteria oredCriterion : oredCriteriaList) {
example.and(oredCriterion);
}
return example;
}