Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Specification or QueryDSL

In one of the projects, we are using Spring Data. Now that the queries are getting complex, we thought about adding Spring Data Specification or QueryDSL.

However, not sure about the best way forward. I think they both serve the same purpose. Is any one is recommended over the other?

Thanks

like image 452
adi Avatar asked Oct 17 '12 11:10

adi


People also ask

What is Querydsl spring?

Querydsl is a framework that enables the construction of statically typed SQL-like queries through its fluent API. Spring Data modules offer integration with Querydsl through QuerydslPredicateExecutor .

What is spring data specification?

SPring Data Jpa Specifications helps us to create dynamic queries based on the requirement at run time. Spring Data Jpa Specifications allows a combination of the attributes or properties of a domain or entity class and creates a query.

What is Querydsl used for?

Querydsl is an extensive Java framework, which allows for the generation of type-safe queries in a syntax similar to SQL. It currently has a wide range of support for various backends through the use of separate modules including JPA, JDO, SQL, Java collections, RDF, Lucene, Hibernate Search, and MongoDB.

What is JPA specification?

Specifications provide us with a way to write reusable queries and also fluent APIs with which we can combine and build more sophisticated queries. All in all, Spring JPA Specifications is a great tool whether we want to create reusable predicates or want to generate typesafe queries programmatically.


1 Answers

Spring Data specifications are a bit verbose compared to Querydsl

public CustomerSpecifications {

  public static Specification<Customer> customerHasBirthday() {
    return new Specification<Customer> {
      public Predicate toPredicate(Root<T> root, CriteriaQuery query, CriteriaBuilder cb) {
        return cb.equal(root.get(Customer_.birthday), today);
      }
    };
  }

  public static Specification<Customer> isLongTermCustomer() {
    return new Specification<Customer> {
      public Predicate toPredicate(Root<T> root, CriteriaQuery query, CriteriaBuilder cb) {
        return cb.lessThan(root.get(Customer_.createdAt), new LocalDate.minusYears(2));
      }
    };
  }
}

compared to this

QCustomer customer = QCustomer.customer;
LocalDate today = new LocalDate();
BooleanExpression customerHasBirthday = customer.birthday.eq(today);
BooleanExpression isLongTermCustomer = customer.createdAt.lt(today.minusYears(2));

If you are going to deal with complex queries you might want to pick Querydsl. I believe it will scale better as it is more compact.

This answer is biased, since I am the maintainer of Querydsl.

like image 87
Timo Westkämper Avatar answered Sep 16 '22 14:09

Timo Westkämper