mettok
mettok

Reputation: 557

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. I used it to make all repository in my application like this: 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. I try to use the example on 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_.createdAtcame from. Any help would be appreciated:)

Upvotes: 2

Views: 5628

Answers (1)

axtavt
axtavt

Reputation: 242786

Customer_ comes from JPA 2.0 static metamodel that should be generated by a special tool such as 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); 

Upvotes: 4

Related Questions