【问题标题】:Spring Data JPA: Generate dynamic querySpring Data JPA:生成动态查询
【发布时间】:2019-02-20 14:03:34
【问题描述】:

我有一个包含一些逻辑数据的实体:

@Entity
public class Person {
  private Long id.
  private String name;
  private int age;
  private String address;
  ...
}

我创建了我的 Spring 数据接口

@Repository
public interface CardInventoryRepository extends JpaRepository<Person , Long> {
}

我的目的是根据我的实体的现有值创建一个动态查询,例如 如果名称为空,则查询为:

select * from Person p  Where p.age=12 AND p.address="adress.."

当地址为空时,查询应该是:

select * from Person p  Where p.age=12 AND p.name="ALI"

我只想使用非空字段提取数据?

是否有任何解决方案使用 spring 数据来构建动态查询? 在此先感谢

【问题讨论】:

    标签: java spring spring-boot spring-data-jpa spring-data


    【解决方案1】:

    基于 Spring 文档https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example

    Query by Example (QBE) 是一种用户友好的查询技术,具有 简单的界面。它允许创建动态查询,并且不允许 要求您编写包含字段名称的查询。事实上,查询 by Example 不需要您通过使用编写查询 完全特定于商店的查询语言。

    定义: 一个示例接受一个数据对象(通常是实体对象或其子类型)和一个如何匹配属性的规范。您可以将 Query by Example 与 JPA 一起使用 存储库。

    为此,让您的存储库接口扩展QueryByExampleExecutor&lt;T&gt;,例如:

    public interface PersonRepository extends CrudRepository<Person, String>, QueryByExampleExecutor<Person> {
    }
    

    以下是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.
    }
    

    用法:

    Example<Person> example = Example.of(new Person("Jon", "Snow"));
    repo.findAll(example);
    
    
    ExampleMatcher matcher = ExampleMatcher.matching().
        .withMatcher("firstname", endsWith())
        .withMatcher("lastname", startsWith().ignoreCase());
    
    Example<Person> example = Example.of(new Person("Jon", "Snow"), matcher); 
    repo.count(example);
    

    更多信息

    【讨论】:

      【解决方案2】:

      是的,请查看 Spring Data 的 QueryDSL 支持。您的用例可以通过 Predicate 来实现。简而言之,您必须创建一个谓词,您将在其中传递非空字段,然后将该谓词传递给一个以 Predicate 作为参数的 findAll 方法。您的存储库接口还必须扩展 QueryDslPredicateExecutor

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-27
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 2017-05-13
        • 1970-01-01
        相关资源
        最近更新 更多