JPA分頁模糊查詢

1、Example: 支持and查詢

// 構建分頁查詢條件
Sort sort = new Sort(Sort.Direction.DESC, "createTime");
PageRequest pageRequest = PageRequest.of(page - 1, rows, sort);
User user = new User();
user.setName(name);
user.setAddress(address);
// 構建查詢對象
ExampleMatcher matcher = ExampleMatcher.matching() 
        .withMatcher("name", GenericPropertyMatchers.contains())
        .withMatcher("address", GenericPropertyMatchers.contains());
Example<Meeting> example = Example.of(user, matcher);
userDao.findAll(example, pageRequest);

此種方式sql語句:

select * from t_user where name like '%name%' and address like '%address%' limit page,rows order by createTime desc

Specification: 支持and和or查詢

Specification<User> specification = (Specification<User>) (root, criteriaQuery, cb) -> {
    Predicate p1 = cb.like(root.get("name"), "%" + text + "%");
    Predicate p2 = cb.like(root.get("address"), "%" + text + "%");
    return cb.or(p1, p2);
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章