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);
};

猜你喜欢

转载自blog.csdn.net/xqnode/article/details/93495362