Spring Data JPA Quick Guide
  • Spring Data JPA 快速指南
  • 配置依赖
  • 配置数据源
  • 数据库编码与词语定序
  • Core Concepts
  • 基本用法
  • Transactions
    • 什么是事务
    • 配置事务(@EnableTransactionManagement)
    • 配置事务(XML)
    • 配置事务(@Transactional)
    • @Transactional 实现细节
    • Transaction and Spring Data JPA
    • 事务隔离
    • 事务传播
  • Query Creation from Method Names
  • Using @Query
  • Sorting and Pagination
  • Projection
  • Specification
  • Query by Example
  • javax.persistence Annotations
    • @OneToOne (bidirectional)
      • Usage
      • PO Serialization
      • Save and Update
      • Nested Projection
      • @MapsId
    • @OneToMany (bidirectional)
    • @OneToMany (unidirectional)
    • @ManyToMany (bidirectional)
      • Many-to-Many Using a Composite Key
由 GitBook 提供支持
在本页

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 是不可变的。

上一页Specification下一页javax.persistence Annotations

最后更新于3年前