if (CollectionUtils.isNotEmpty(requestMqInfo.getNameWithIp())) { List<Criteria> criteriaList = new ArrayList<>(); for (MqQueueName mqQueueName : requestMqInfo.getNameWithIp()) { Criteria criteriaToName = Criteria.where("name").is(mqQueueName.getName()) .and("server").is(mqQueueName.getServer()); criteriaList.add(criteriaToName); } Criteria criteriaToAllName = new Criteria().orOperator(criteriaList.toArray(new Criteria[criteriaList.size()])); Criteria criteria = Criteria.where("monitorDate").gte(requestMqInfo.getWatchTimeStart()) .lte(requestMqInfo.getWatchTimeEnd()) .andOperator(criteriaToAllName); } else { Criteria criteria = Criteria.where("monitorDate").gte(requestMqInfo.getWatchTimeStart()) .lte(requestMqInfo.getWatchTimeEnd()); } //按时间升序排序 Sort sort = Sort.by(Sort.Order.asc("monitorDate")); Query query = Query.query(criteria).with(sort); 不好意思刚才忘了
时间: 2024-02-10 09:12:56 浏览: 64
Criteria(hibernate3.0).rar_Criteria java_criteria Hibernate_hibe
问题出在 `criteria` 变量的作用域。在第一个if语句块中定义的 `criteria` 变量仅在该块中有效,当程序执行到第二个else语句块中时,尝试访问该变量会提示未定义错误。解决方法是将 `criteria` 变量定义在if/else语句块之外,如下所示:
```
Criteria criteria;
if (CollectionUtils.isNotEmpty(requestMqInfo.getNameWithIp())) {
//...
criteria = Criteria.where("monitorDate").gte(requestMqInfo.getWatchTimeStart())
.lte(requestMqInfo.getWatchTimeEnd())
.andOperator(criteriaToAllName);
} else {
criteria = Criteria.where("monitorDate").gte(requestMqInfo.getWatchTimeStart())
.lte(requestMqInfo.getWatchTimeEnd());
}
//按时间升序排序
Sort sort = Sort.by(Sort.Order.asc("monitorDate"));
Query query = Query.query(criteria).with(sort);
```
这样就可以使得 `criteria` 变量在if/else语句块之外也能被访问到。
阅读全文