adi
adi

Reputation: 1741

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

Upvotes: 18

Views: 7545

Answers (1)

Timo Westkämper
Timo Westkämper

Reputation: 22190

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.

Upvotes: 28

Related Questions