Spring Data JPA:生成动态查询

问题描述 投票:1回答:2

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

@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> {
}

我的目的是基于我的实体的现有值创建动态查询,例如,如果名称为null,则查询为:

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

当地址为null时,查询应为:

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

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

是否有任何解决方案起诉弹簧数据来构建动态查询?提前致谢

java spring spring-boot spring-data-jpa spring-data
2个回答
2
投票

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

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

定义:示例采用数据对象(通常是实体对象或其子类型)和规范如何匹配属性。您可以使用JPA存储库查询示例。

为此,请让您的存储库接口扩展QueryByExampleExecutor<T>,例如:

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
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.