Query by Example

注意:前面我们看到,JpaRepository 继承了 QueryByExampleExecutor,如果你自己的 Repository 继承了 JpaRepository,那么默认即会拥有 Query by Example 的能力。

使用例子来执行动态查询,不需要编写任何的查询语句。

Query by Example API 包含下列三个部分:

  • Probe: 实体类的一个 Example

  • ExampleMatcher: 匹配规则

  • Example: 包含 Probe 和 ExampleMatcher,用于创建查询

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.

使用默认 ExampleMatcher:

User user = new User(); // Probe
user.setUsername("admin");

Example<User> example = Example.of(user); // Example

List<User> list = userRepository.findAll(example); // Query
System.out.println(list);

默认情况下,null 值属性将被忽略。

自定义 ExampleMatcher:

User user = new User(); // Probe
user.setUsername("y");
user.setAddress("sh");
user.setPassword("admin");

ExampleMatcher matcher = ExampleMatcher.matching() // ExampleMatcher
    .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.startsWith())//模糊查询匹配开头,即{username}%
    .withMatcher("address" ,ExampleMatcher.GenericPropertyMatchers.contains())//全部模糊查询,即%{address}%
    .withIgnorePaths("password");//忽略字段,即不管password是什么值都不加入查询条件

Example<User> example = Example.of(user ,matcher); // Example

List<User> list = userRepository.findAll(example); // Query
System.out.println(list);

Example 是不可变的。

最后更新于