Spring Data JPA + Querydsl Integration : Part 1

Sonu Patel
Tech2flew
Published in
2 min readDec 12, 2019

--

Querydsl is a framework which enables the construction of type-safe SQL-like queries for multiple backends including JPA, MongoDB and SQL in Java.

Instead of writing queries as inline strings or externalizing them into XML files they are constructed via a fluent API.

Spring Data has been coming with ready made integration with the Querydsl through its Repository. Querydsl is a framework which enables the construction of type-safe SQL-Like queries for multiple backends including JPA, MongoDB and SQL in Java.

Instead of writing queries as inline strings or externalizing them into XML files, they are constructed via a fluent API. What you have to do is by extending your custom Repository through extends QueryDslPredicateExecuter, this will pull methods like findAll(Predicate predicate) and findOne(Predicate predicate) into the API. We now have everything in place, so we can actually start using the generated classes. To generate your meta model through using of JPAAnnotationProcessor for being able to execute a predicate queries.

Best Way to Configuring Querydsl with Repository.

There is no necessary xml or any annotation to configure Querydsl. Bellow some points points to configure.
Configure your maven pom.xml file by including the required maven plugin. That plugin should be used for generating your Meta Model classes from your entities. That plugin will search about all of those annotated @Embeddable, @Entity or relationship between Entities and generates a list of Meta Model classes that located under your provided location as you’ll see.

  • Add the required libraries for Querydsl; querydsl has been coming with a lot of libraries for serving the different kinds of persistence stores. Libraries such as querydsl-core, querydsl-apt and querydsl-jpa are the required libraries, cause we are going to use the Querydsl with the JPA.
  • Compulsory to extension Repository by extending the QueryDslPredicateExecutor, that’s generic interface has given the developer ability to provide it the entity that it being processed in its query.

Here i attached pom.xml dependecy.

<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-core</artifactId>
<version>3.3.2</version>
</dependency>

<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>3.3.2</version>
</dependency>

<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>3.3.2</version>
</dependency>

Now moved to Repository class for extension

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer>,QueryDslPredicateExecutor<Employee>{
public Employee findByEmployeeId(Integer id);
}

--

--

Sonu Patel
Tech2flew

Building thrill in tech my soul is made from tech .