动态查询之Example
官方文档介绍
The Query by Example API consists of three parts:
- Probe: The actual example of a domain object with populated fields.
- ExampleMatcher: The ExampleMatcher carries details on how to match particular fields. It can be reused across multiple Examples.
- Example: An Example consists of the probe and the ExampleMatcher. It is used to create the query.
Query by Example is well suited for several use cases:
- Querying your data store with a set of static or dynamic constraints.
- Frequent refactoring of the domain objects without worrying about breaking existing queries.
- Working independently from the underlying data store API.
Query by Example also has several limitations:
- No support for nested or grouped property constraints, such as firstname = ?0 or (firstname = ?1 and lastname = ?2).
- Only supports starts/contains/ends/regex matching for strings and exact matching for other property types.
使用
UUser user = new UUser();
user.setUserName("e");
user.setStatus(1);
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())//模糊查询匹配开头,即{userNamee}%
;
Example<UUser> userExample = Example.of(user, matcher);
userRepository.findAll(userExample);
上述设置将模糊匹配 userName包含‘e’,且status等于1 的全部对象
上例中设置匹配器规则,也可使用默认的匹配器规则,默认是属性不为空的就根据属性值进行查询
匹配器规则
Matching | 生成的语句 | 说明 |
---|---|---|
DEFAULT (case-sensitive) | firstname = ?0 | 默认(大小写敏感) |
DEFAULT (case-insensitive) | LOWER(fir |