Spring-Data-JPA 用Specification进行动态SQL查询
1.定义一个继承JpaSpecificationExecutor的接口
public interface UserDao extends JpaRepository<User, Integer>,JpaSpecificationExecutor<User>{}
这里只是继承接口中的方法:
T findOne(Specification<T> spec);
List<T> findAll(Specification<T> spec);
Page<T> findAll(Specification<T> spec, Pageable pageable);
List<T> findAll(Specification<T> spec, Sort sort);
long count(Specification<T> spec);
定义了常用的查询单个对象,查询数据集合,查询分页数据集合,查询带排序参数的数据集合,查询数据的大小。
2.UserService.java增加如下方法代码
/**
* 动态参数分页,分页查询
* @return
*/
public Page<User> find(final User user, Pageable pageable) {
return userDao.findAll(new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>();
// 模糊查询
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()]):至于为什么要这样写参考源码例子
*/
/* 考源码例子:
* <pre>{@code String[] y = x.toArray(new String[0]); }</pre>
*
* Note that <tt>toArray(new Object[0])</tt> is identical in
* function to <tt>toArray()</tt>.
*/
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<User> find = userService.find(param, pageRequest);
List<User> content = find.getContent();
for (User user : content) {
System.out.println(user);
}
}
JAVA程序猿成长之路
分享学习资源,学习方法,记录程序员生活。