一、简介
按例查询(Query By Example
)是一种用户界面友好的查询技术。 它允许 动态创建 查询,并且不需要编写包含字段名称的查询。 实际上,按示例查询 不需要 使用特定的数据库的查询语言来编写查询语句。
1、按例查询(QBE)由三部分组成:
Probe
:带有填充字段的域对象的实际示例(即 实体)ExampleMatcher
:ExampleMatcher
提供关于如何匹配特定字段的详细信息,它可以跨多个示例重用Example
:示例包括Probe
和ExampleMatcher
,它用于创建查询
2、优势:
- 使用一组静态或动态约束查询数据存储
- 可以频繁地重构域对象,而不用担心破坏现有的查询
- 独立于底层数据存储
API
工作
3、限制:
-
不支持嵌套或分组属性约束
firstname = ?0 or (firstname = ?1 and lastname = ?2)
-
只支持字符串的
starts/contains/ends/regex
匹配和其他属性类型的精确匹配即不支持查询 时间段 、数组范围 等条件
二、使用
1、构建简单的 Example:
Person person = new Person();
person.setFirstname("Dave");
Example<Person> example = Example.of(person); // 此处未构建自定义匹配规则,使用的是默认匹配规则
2、实现 QueryByExampleExecutor
接口,并执行查询:
public interface QueryByExampleExecutor<T> {
<S extends T> S findOne(Example<S> example);
<S extends T> Iterable<S> findAll(Example<S> example);
// … more functionality omitted.
}
public interface PersonRepository extends JpaRepository<Person, String> { … }
public class PersonService {
@Autowired PersonRepository personRepository;
public List<Person> findPeople(Person probe) {
return personRepository.findAll(Example.of(probe));
}
}
3、ExampleMatcher
的匹配规则:
一个 ExampleMatcher
示例:
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("name", match -> match.endsWith()) // name like %?0
.withMatcher("address", match -> match.startsWith()); // address like ?0%
// 使用方法引用设置匹配规则
.withMatcher("sex", ExampleMatcher.GenericPropertyMatcher::contains) // sexlike %?%
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l3PmOxMj-1606200565478)(C:\Users\ZhuXY\AppData\Roaming\Typora\typora-user-images\image-20201124144008660.png)]