Probe、ExampleMatcher 和 Example
Probe:这是具有填充字段的域对象的实际实体类,即查询条件的封装类(又可以理解为查询条件参数),必填。
ExampleMatcher:ExampleMatcher 有关如何匹配特定字段的匹配规则,它可以重复使用在多个实例中,必填。
Example:Example 由 Probe 探针和 ExampleMatcher 组成,它用于创建查询,即组合查询参数和参数的匹配规则。
public interface Example<T> {
static <T> Example<T> of(T probe) {
return new TypedExample<>(probe, ExampleMatcher.matching());
}
static <T> Example<T> of(T probe, ExampleMatcher matcher) {
return new TypedExample<>(probe, matcher);
}
//实体参数
T getProbe();
//匹配器
ExampleMatcher getMatcher();
//回顾一下我们上一课时讲解的类型,这个是返回实体参数的Class Type;
@SuppressWarnings("unchecked")
default Class<T> getProbeType() {
return (Class<T>) ProxyUtils.getUserClass(getProbe().getClass());
}
}
通过 Example 的源码,我们发现想创建 Example 的话,只有两个方法:
1、static Example of(T probe):需要一个实体参数,即查询的条件。而里面的 ExampleMatcher 采用默认的 ExampleMatcher.matching(); 表示忽略 Null,所有字段采用精准匹配。
2、static Example of(T probe, ExampleMatcher matcher):需要两个参数构建 Example,也就表示了 ExampleMatcher 自由组合规则,正如我们上面的测试用例里面的代码一样。
ExampleMatcher,分析一下它的语法:
打开 Structure 视图,具体有的方法如下:
初始化 ExampleMatcher 实例的方法
一共有三个:
//默认matching方法
static ExampleMatcher matching() {
return matchingAll();
}
//matchingAll,默认的方法
static ExampleMatcher matchingAll() {
return new TypedExampleMatcher().withMode(MatchMode.ALL);
}
static ExampleMatcher matchingAny() {
return new TypedExampleMatcher().withMode(MatchMode.ANY);
}
前两个方法所表达的意思是一样的,只不过一个是默认,一个是方法名上面有语义的。两者采用的都是 MatchMode.ALL 的模式,即 AND 模式。第三个 MatchMode.ANY,表示查询条件是 or 的关系。
ExampleMatcher 语法给我们暴露的方法
1、忽略大小写
//默认忽略大小写的方式,默认 False。
ExampleMatcher withIgnoreCase(boolean defaultIgnoreCase);
//提供了一个默认的实现方法,忽略大小写;
default ExampleMatcher withIgnoreCase() {
return withIgnoreCase(true);
}
//哪些属性的paths忽略大小写,可以指定多个参数;
ExampleMatcher withIgnoreCase(String... propertyPaths);
2、NULL 值的 property处理
ExampleMatcher withNullHandler(NullHandler nullHandler);
参数 NullHandler枚举值有两个可选值:INCLUDE(包括)、IGNORE(忽略),其中要注意:
标识作为条件的实体对象中,一个属性值(条件值)为 Null 时,是否参与过滤;
当该选项值是 INCLUDE 时,表示仍参与过滤,会匹配数据库表中该字段值是 Null 的记录;
若为 IGNORE 值,表示不参与过滤。
//提供一个默认实现方法,忽略 NULL 属性;
default ExampleMatcher withIgnoreNullValues() {
return withNullHandler(NullHandler.IGNORE);
}
//把 NULL 属性值作为查询条件
default ExampleMatcher withIncludeNullValues() {
return withNullHandler(NullHandler.INCLUDE);
}
3、忽略某些 Paths,不参加查询条件
//忽略某些属性列表,不参与查询过滤条件。
ExampleMatcher withIgnorePaths(String... ignoredPaths);