4.30.2015

How to use QueryDSL with JPA, Gradle and IDEA

QueryDSL is cool Database Query DSL for Java. I will recommend you to check it if you still don't know what is it. But there are not so much information on how to use it with Gradle. Also, it's not so clear about Intellij IDEA integration. With this article I would like to point you on querydsl-apt and Java annotations processors discovery.

Similar to projects like Lombok since version 2.7.1 QueryDSL has support for Java annotation processors discovery: https://github.com/querydsl/querydsl/issues/180. It means that we don't have to configure code generation manually, javac will pick up annotation processor automagically.

Gradle

Gradle setup is really easy. You can start with example project created by me: https://github.com/bsideup/querydsl-gradle-idea/tree/10ffd70805e3a7951d4614ff4f7e27102fdad343

build.gradle is simple:


We're declaring dependency on querydsl-apt:3.6.3 with jpa classifier. It contains Java Annotation Processor for JPA annotations like @Entity. If you already have a project with QueryDSL and just want to improve your Gradle build - just remove everything related to QueryDSL code generation and just add this dependency.

Now you can build your project:

$ ./gradlew build
:compileJava
Note: Running JPAAnnotationProcessor
Note: Serializing Entity types
Note: Generating ru.trylogic.querydsl.example.QUser for [ru.trylogic.querydsl.example.User]
Note: Running JPAAnnotationProcessor
Note: Running JPAAnnotationProcessor
:processResources
:classes
:jar
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build

BUILD SUCCESSFUL

Total time: 2.768 secs

There are notes about annotation processing from JPAAnnotationProcessor. It means that everything works as expected and code was generated. Easy, huh?

IntelliJ IDEA

But we don't want to build our project with Gradle during development, we want to use build from IDEA! First, change your build.gradle file:


Now open project in IDEA (if you didn't import project yet you can easily open build.gradle file in IDEA, it will propose you to import it). For some reasons IDEA will not enable annotation processing by default when you import your Gradle project, so you need to enable it.

  1. Go to Preferences -> Build, Execution, Deployment -> Annotation Processors;
  2. Check Enable annotation processing checkbox;
  3. In "Store generated sources relative to:" select Module content root.
Now if you will build your project, QueryDSL will generate code for your entities and you will be able to use it like this:



As always, full sources can be found here: http://github.com/bsideup/querydsl-gradle-idea/