代码之家  ›  专栏  ›  技术社区  ›  e2rabi

Spring数据JPA:生成动态查询

  •  1
  • e2rabi  · 技术社区  · 6 年前

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

    例如,我的目的是基于实体的exist值创建一个动态查询

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

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

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

    提前谢谢

    2 回复  |  直到 6 年前
        1
  •  2
  •   MohammadReza Alagheband    6 年前

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

    示例查询(QBE)是一种用户友好的查询技术 要求您编写包含字段名的查询。实际上,查询 例如,不需要使用 存储特定的查询语言。

    定义:

    为此,请扩展存储库接口 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
  •  2
  •   user10367961 user10367961    6 年前

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