I'm new to Spring data JPA and am trying to understand how to best use it with QueryDSL. Without QueryDSL, I would be able to simply create any queries in my SpringData interface with an @Query annotation.
In order to have the same experience using QueryDSL, from what I can see, I need to either create my own custom repository implementation and have my repo interface extend my custom implementation interface or put all my QueryDSL queries at a service layer which wraps my repo.
In the first case, I lose the ability to use any of the SD autogenerated methods (ex: findAll(QueryDSL predicate) ) in my custom repo since I don't have access to the actual repo object, and in the second case I am putting query logic at the service layer instead of at the repo layer.
Neither solution sounds particularly attractive to me. Is there a 3rd way that is more appropriate? Or am I misunderstanding how to properly use QueryDSL and Spring Data?
Thanks!
Eric
Querydsl is an extensive Java framework, which helps with creating and running type-safe queries in a domain specific language that is similar to SQL. In this article we'll explore Querydsl with the Java Persistence API.
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 .
Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that's actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.
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.
Probably the most convenient way is to let your repository interfaces simply extend QueryDslPredicateExecutor
which adds the capability to simply pipe Querydsl Predicate
objects into the repository and execute them standalone or alongside Pageable
and Sort
and the like.
If you really want to hide the combination of predicates into the repository layer (which is absolutely fine but actually serves a different purpose) you create a separate repository implementation class as described here and use QueryDslRepositorySupport
as base class. In your implemented finder methods you can then just use the from(…)
, update(…)
and delete(…)
methods of the base class to easily construct and execute queries using the Querydsl meta-model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With