简体   繁体   English

如何通过spring-data-jpa框架进行自定义搜索?

[英]How to make a custom search by spring-data-jpa framework?

I am very new to use spring-data-jpa, but it looks very promising. 我对使用spring-data-jpa非常陌生,但看起来非常有前途。 I used it to make all repository in my application like this: public interface CustomerRepository extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer> 我用它来使应用程序中的所有存储库如下所示: public interface CustomerRepository extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer>

I see that there is a methode call findAll(Specification<T>) to make custom search.to call this you should implement the public Predicate toPredicate(Root<T> root, CriteriaQuery<?> q, CriteriaBuilder cb) I am very confused to how to make a predicate. 我看到有一个方法调用findAll(Specification<T>)进行自定义搜索。要调用此方法,您应该实现public Predicate toPredicate(Root<T> root, CriteriaQuery<?> q, CriteriaBuilder cb)我很困惑如何做一个谓词。 I try to use the example on Spring 我尝试在Spring上使用该示例

  public static Specification<Customer> isLongTermCustomer() {
return new Specification<Customer>() {
  Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
        CriteriaBuilder builder) {

     LocalDate date = new LocalDate().minusYears(2);
     return builder.lessThan(root.get(Customer_.createdAt), date);
  }
};

} I dont understand where Customer_.createdAt came from. }我不明白Customer_.createdAt来源。 Any help would be appreciated:) 任何帮助,将不胜感激:)

Customer_ comes from JPA 2.0 static metamodel that should be generated by a special tool such as Hibernate Metamodel generator . Customer_来自JPA 2.0静态元模型,应该由诸如Hibernate Metamodel generator之类的特殊工具来生成

If you don't want to generate static metamodel, you can do the following instead: 如果您不想生成静态元模型,则可以执行以下操作:

return builder.lessThan(root.<LocalDate>get("createdAt"), date); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM