话不多说,直接上代码:
Query query = new Query();
query.fields().include("_id").include("typeCode").include("nameDesc").include("ipVal").include("enblFlag");//指定查询字段
query.skip((pageNo - 1) * pageSize);//便宜记录数
query.limit(pageSize);//每页记录数
query.with(Sort.by("nameDesc"));//指定排序字段,默认升序
if (!StringUtils.isEmpty(equipmentInfo.getNameDesc())) {
Pattern pattern = Pattern.compile("^.*" + escapeExprSpecialWord(equipmentInfo.getNameDesc().trim()) + ".*$", Pattern.CASE_INSENSITIVE);
query.addCriteria(Criteria.where("nameDesc").regex(pattern));//模糊查询
}
/**
* 转义字符串中与正则表达式相关的特殊字符
*/
public String escapeExprSpecialWord(String keyword) {
String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
for (String key : fbsArr) {
if (keyword.contains(key)) {
keyword = keyword.replace(key, "\\" + key);
}
}
return keyword;
}
也可以使用一下代码设置排序方式:
query.with(Sort.by(Sort.Direction.ASC, "nameDesc"));
//或
query.with(Sort.by(Sort.Direction.DESC, "nameDesc"));