Based on the previous article SpringData JPA entry demo , we continue to learn more about Specifications dynamic query.
Based on the development environment established in the previous article, we then create a new test package to learn the dynamic query entry demo of the Specifications interface
1. Create a new test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest {
@Autowired
private CustomerDao customerDao;
}
1. Single condition query object- equal(String str, String str);
@Test
public void testFindByCondition() {
Specification<Customer> spec = new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
Predicate predicate = cb.equal(custName, "张三");
return predicate;
}
};
Customer customer = customerDao.findOne(spec);
System.out.println(customer);
}
2. Multi-condition query object- and(Predicate p1, Predicate p2); or(Predicate p1, Predicate p2);
@Test
public void testFindBySeveralCondition() {
Specification<Customer> spec = new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
Path<Object> custIndustry = root.get("custIndustry");
Predicate p1 = cb.equal(custName, "张三");
Predicate p2 = cb.equal(custIndustry, "it行业");
Predicate and = cb.and(p1, p2); //以 与 的形式拼接多个查询条件
//Predicate or = cb.or(p1, p2); //以 或 的形式拼接多个查询条件
return and;
}
};
Customer customer = customerDao.findOne(spec);
System.out.println(customer);
}
3. Fuzzy query- like();
Sort- Sort sort = new Sort(Sort.Direction.DESC, sorted field name);
@Test
public void testLike() {
Specification<Customer> spec = new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
Predicate like = cb.like(custName.as(String.class), "张%");
return like;
}
};
//添加排序
//Sort.Direction.DESC: 倒序
//Sort.Direction.ASC: 升序
Sort sort = new Sort(Sort.Direction.DESC, "custName");
List<Customer> list = customerDao.findAll(spec, sort);
for (Customer customer : list) {
System.out.println(customer);
}
}
4. Paging query
@Test
public void testPage() {
Specification spec = null;
Pageable pageable = new PageRequest(0, 10);
Page<Customer> page = customerDao.findAll(null, pageable);
System.out.println(page.getContent()); //得到数据集合列表
System.out.println(page.getTotalElements()); //得到总条数
System.out.println(page.getTotalPages()); //得到总页数
}
Source download: https://pan.baidu.com/s/1JLc4zABzZBzoy4JhJNNJpg