QueryByExampleExecutor 的使用
按示例查询(QBE)是一种用户友好的查询技术,具有简单的接口,它允许动态查询创建,并且不需要编写包含字段名称的查询。从 UML 图中,可以看出继承 JpaRepository 接口后,自动拥有了按“实例”进行查询的诸多方法,可见 Spring Data 的团队已经认为了 QBE 是 Spring JPA 的基本功能了,继承 QueryByExampleExecutor 和继承 JpaRepository 都会有这些基本方法,所以 QueryByExampleExecutor 位于 Spring Data Common 中,而 JpaRepository 位于 Spring Data JPA 中。
QueryByExampleExecutor 详细配置
先来看一下 QueryByExampleExecutor 的源码:
public interface QueryByExampleExecutor<T> {
//根据“实例”查找一个对象。
<S extends T> S findOne(Example<S> example);
//根据“实例”查找一批对象
<S extends T> Iterable<S> findAll(Example<S> example);
//根据“实例”查找一批对象,且排序
<S extends T> Iterable<S> findAll(Example<S> example, Sort sort);
//根据“实例”查找一批对象,且排序和分页
<S extends T> Page<S> findAll(Example<S> example, Pageable pageable);
//根据“实例”查找,返回符合条件的对象个数
<S extends T> long count(Example<S> example);
//根据“实例”判断是否有符合条件的对象
<S extends T> boolean exists(Example<S> example);
}
从源码上可以看出,只要了解 Example 基本上就可以掌握它的用法和 API 了。
public class Example<T> {
@NonNull
private final T probe;
@NonNull
private final ExampleMatcher matcher;
public static <T> Example<T> of(T probe) {
return new Example(probe, ExampleMatcher.matching());
}
public static <T> Example<T> of(T probe, ExampleMatcher matcher) {
return new Example(probe, matcher);
}
......
}
我们从源码中可以看出 Example 主要包含三部分内容。
- Probe:这是具有填充字段的域对象的实际实体类,即查询条件的封装类(又可以理解为:查询条件参数),必填。
- ExampleMatcher:ExampleMatcher 有关于如何匹配特定字段的匹配规则,它可以重复使用在多个示例,必填;如果不填,用默认的(又可以理解为参数的匹配规则)。
- Example:Example 由 Probe 探针和 ExampleMatcher 组成,它用于创建查询,即组合查询参数和参数的匹配规则。
QueryByExampleExecutor 的使用案例
//创建查询条件数据对象
Customer customer = new Customer();
customer.setName("Jack");
customer.setAddress("上海");
//创建匹配器,即如何使用查询条件
ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
.withMatcher("name", GenericPropertyMatchers.startsWith()) //姓名采用“开始匹配”的方式查询
.withIgnorePaths("focus"); //忽略属性:是否关注。因为是基本类型,需要忽略掉
//创建实例
Example<Customer> ex = Example.of(customer, matcher);
//查询
List<Customer> ls = dao.findAll(ex);
//输出结果
for (Customer bo:ls) {
System.out.println(bo.getName());
}
上面例子中,是这样创建“实例”的:
Example<Customer> ex = Example.of(customer, matcher);
可以看到,Example 对象由 customer 和 matcher 共同创建,为讲解方便,再来结合案例先来明确一些定义。
- Probe:实体对象,在持久化框架中与 Tab