Spring-Data-JPA 用Specification进行动态SQL查询

1.定义一个继承JpaSpecificationExecutor的接口

public interface UserDao extends JpaRepository,JpaSpecificationExecutor{}

这里只是继承接口中的方法:

T findOne(Specification spec);

List findAll(Specification spec);

Page findAll(Specification spec, Pageable pageable);

List findAll(Specification spec, Sort sort);

long count(Specification spec);

定义了常用的查询单个对象,查询数据集合,查询分页数据集合,查询带排序参数的数据集合,查询数据的大小。

2.UserService.java增加如下方法代码

    /**
     * 动态参数分页,分页查询
     * @return
     */
public Page find(final User user, Pageable pageable) {
return userDao.findAll(new Specification() {


@Override
public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
List predicates = new ArrayList();
// 模糊查询
if (StringUtils.isNotBlank(user.getName())) {
predicates.add(cb.like(root.get("name").as(String.class), "%" + user.getName() + "%"));
}
// gt大于查询
if (user.getAge() != null) {
predicates.add(cb.gt(root.get("age").as(Integer.class), user.getAge()));

}

                       /*
* Create a conjunction of the given restriction predicates
* 创建给定限制predicates的连接。 cb.and()接收一个Predicates数组,连接每一个查询条件
* predicates.toArray(new
* Predicate[predicates.size()]):至于为什么要这样写参考源码例子
*/
/* 考源码例子:

{@code String[] y = x.toArray(new String[0]); }

*
* Note that toArray(new Object[0]) is identical in
* function to toArray().
*/
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
}, pageable);

}

3.测试代码

       @Test
public void test12() {
PageRequest pageRequest = new PageRequest(0, 100);
User param = new User();
param.setAge(20);
param.setName("李四");
Page find = userService.find(param, pageRequest);
List content = find.getContent();
for (User user : content) {
System.out.println(user);
}
}

               

微信公众号

                          

你可能感兴趣的:(spring-data-jpa,spring-boot,mysql)