SpringBoot JPA实践之Specification查询分页
2020-05-01 22:15:42
阅读:()
前文在介绍全量API函数的时候有列出来findAll函数中有个Specification类型的参数,它也是JPA实现的基于对象查询的动态查询方式,它可以实现多表级联情况的参数查询,但由于个人不喜欢在Entity中配置一对一、一对多等场景,故不对其关联对象的查询实现做深入研究,实际应用的时候写SQL查询本站有提供另外一种非常方便的实现。
代码实现
Dao
/**
* Specification查询
*
* @author chendd
* @date 2020/5/2 22:18
*/
@Repository
public class UserPageDao {
@Resource
private UserRepository userRepository;
public Page<User> queryUsersPage(final User user , Integer page , Integer size) {
Pageable pageable = PageRequest.of(page , size , Sort.by("name"));
Page<User> pager = userRepository.findAll((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicateList = new ArrayList<>();
//动态构造查询条件
String name = user.getName();
if(StringUtils.isNotEmpty(name)) {
predicateList.add(criteriaBuilder.equal(root.get("name") , name));
}
String email = user.getEmail();
if(StringUtils.isNotEmpty(email)) {
predicateList.add(criteriaBuilder.like(root.get("email") , email + "%"));
}
Predicate[] predicates = new Predicate[predicateList.size()];
predicateList.toArray(predicates);
return criteriaQuery.where(predicates).getRestriction();
}, pageable);
return pager;
}
}
Test
/**
* Predicate查询分页
*
* @author chendd
* @date 2020/5/2 22:43
*/
public class UserPredicatePageTest extends ApplicationTest {
@Resource
private UserPageDao dao;
@Test
public void testUserPredicatePage() {
User user = new User();
user.setName("chendd"); //等值查询
user.setEmail("886"); //模糊查询
Page<User> page = dao.queryUsersPage(user, 0, 5);
Assert.assertNotNull(page.getContent());
}
}
你可能感兴趣的:
互动()
评论()
比起点赞,站长更喜欢登录后的评论
-
0 -
0 -
0 -
0 -
0