Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added querydsl tutorial #194

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions querydsl/files/FruitFragment.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package org.acme.spring.data.jpa.repo.fruit;

import java.util.List;

import org.acme.spring.data.jpa.model.Fruit;

public interface FruitFragment {

public List<Fruit> findAllQueryDslName(String name);

public List<Fruit> findAllQueryDslMaxPriceDesc(Float price);

public List<Fruit> findAllQueryDslMinPriceAsc(Float price);

public List<Fruit> findAllQueryDslPriceRange(Float min, Float max);

}
67 changes: 67 additions & 0 deletions querydsl/files/FruitFragmentImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package org.acme.spring.data.jpa.repo.fruit;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import org.acme.spring.data.jpa.model.Fruit;
import org.acme.spring.data.jpa.model.QFruit;

import com.querydsl.jpa.impl.JPAQuery;

public class FruitFragmentImpl implements FruitFragment {

@Inject
EntityManager em;

@Override
public List<Fruit> findAllQueryDslName(String name) {

QFruit fruit = QFruit.fruit;
JPAQuery<Fruit> query = new JPAQuery<Fruit>(this.em);
query.from(fruit);
if (name != null && !name.isEmpty()) {
query.where(fruit.name.eq(name));
}
return query.orderBy(fruit.name.desc()).fetch();
}

@Override
public List<Fruit> findAllQueryDslMaxPriceDesc(Float price) {

QFruit fruit = QFruit.fruit;
JPAQuery<Fruit> query = new JPAQuery<Fruit>(this.em);
query.from(fruit);
if (price != null && price != 0) {
query.where(fruit.price.loe(price));
}
return query.orderBy(fruit.price.desc()).fetch();
}

@Override
public List<Fruit> findAllQueryDslMinPriceAsc(Float price) {

QFruit fruit = QFruit.fruit;
JPAQuery<Fruit> query = new JPAQuery<Fruit>(this.em);
query.from(fruit);
if (price != null && price != 0) {
query.where(fruit.price.goe(price));
}
return query.orderBy(fruit.price.asc()).fetch();
}

@Override
public List<Fruit> findAllQueryDslPriceRange(Float min, Float max) {

QFruit fruit = QFruit.fruit;
JPAQuery<Fruit> query = new JPAQuery<Fruit>(this.em);
query.from(fruit);
if (min != null && min != 0 && max != null && max != 0) {
query.where(fruit.price.between(min, max));
}
return query.orderBy(fruit.price.desc()).fetch();
}

}
34 changes: 34 additions & 0 deletions querydsl/files/findAllQueryDslFunc.asciidoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
Now we can implement Querydsl-queries in the `FruitFragmentImpl`. The class requires a JPA `EntityManager` to interact with the persistent entities, which is passed to the `JPAQuery` constructor when instantiating a query.

In order to define the `Fruit`-entity as the source of the query, we need to create its Q-type first by accessing its static `fruit` field. Then, we can call `query.from(fruit)`.

To retrieve a fruit with a given name, we can use a `where`-clause with the `eq` (equals) operator to get fruits with the name equal to the one passed to the function parameter. Additionally, we can sort the results by name in descending alphabetical order by calling `query.orderBy(fruit.name.desc())` before fetching the result.

public class FruitFragmentImpl implements FruitFragment {

@Inject
EntityManager em;

@Override
public List<Fruit> findAllQueryDslName(String name) {

JPAQuery<Fruit> query = new JPAQuery<Fruit>(this.em);
QFruit fruit = QFruit.fruit;
query.from(fruit);
if (name != null && !name.isEmpty()) {
query.where(fruit.name.eq(name));
}
return query.orderBy(fruit.name.desc()).fetch();
}

We can also get fruits in a given price range by calling `fruit.price.between(min, max)` in the `where`-clause. To see usage of further comparators, see the `findAllQueryDslMaxPriceDesc`and `findAllQueryDslMinPriceAsc` functions.

@Override
public List<Fruit> findAllQueryDslPriceRange(Float min, Float max) {
...
if (min != null && min != 0 && max != null && max != 0) {
query.where(fruit.price.between(min, max));
}
return query.orderBy(fruit.price.desc()).fetch();
}

1 change: 1 addition & 0 deletions querydsl/files/function.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
return this.fruitRepository.findAllQueryDslName(name);
16 changes: 16 additions & 0 deletions querydsl/files/querydsl-annotation-processor.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
11 changes: 11 additions & 0 deletions querydsl/files/querydsl-dependencies.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.1.3</version>
</dependency>
94 changes: 94 additions & 0 deletions querydsl/index.asciidoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
= Querydsl Tutorial
====
This tutorial will teach you how to integrate link:https://querydsl.com/[Querydsl] into a Spring or Quarkus project and how to build Querydsl queries.
## Prerequisites
* Installed devonfw IDE
* User should have basic Java development experience

## Learning goals.
Here in this tutorial you will learn
* To integrate Querydsl in your project
* To build Querydsl expressions
====

[step]
--
restoreDevonfwIde(["java","mvn"])
--

====
devonfw-ide has been installed for you.

First, clone the `QueryDslTutorial` repository from GitHub. It contains an application with a simple REST service.
[step]
== Clone QueryDslTutorial repository
--
cloneRepository("", "https://github.com/EduardKrieger/QueryDslTutorial.git")
--

In order to use Querydsl, we need to add the Querydsl dependencies to our Maven project and configure the Maven APT plugin.
The JPAAnnotationProcessor will find domain types annotated with the javax.persistence.Entity annotation and generate query types for them.
====

[step]
== Add Querydsl dependencies to Maven Project
--
changeFile("QueryDslTutorial/pom.xml" , {"file": "files/querydsl-dependencies.txt", "placeholder": "<QueryDslDependencies>"})
changeFile("QueryDslTutorial/pom.xml" , {"file": "files/querydsl-annotation-processor.txt", "placeholder": "<AnnotationProcessor>"})
--

Next, navigate to the devonfw/QueryDslTutorial directory.
[step]
--
changeWorkspace("devonfw/workspaces/main/QueryDslTutorial")
--

The data model consists of a Fruit entity with Id, name, color, and price fields.

To extend the application with custom queries in Querydsl, we need to create a FruitFragment-interface and its implementation. This will be extended by the FruitRepository along with the CrudRepository.

[step]
== Create FruitFragment Interface
--
createFile("src/main/java/org/acme/spring/data/jpa/repo/fruit/FruitFragment.java","files/FruitFragment.java")
--

[step]
== Extend FruitRepository with FruitFragment Interface
--
changeFile("src/main/java/org/acme/spring/data/jpa/repo/fruit/FruitRepository.java", {"content": "public interface FruitRepository extends CrudRepository<Fruit, Long>, FruitFragment {", "placeholder": "public interface FruitRepository extends CrudRepository<Fruit, Long> {"})
--

[step]
== Implement FruitFragment Interface
--
createFile("src/main/java/org/acme/spring/data/jpa/repo/fruit/FruitFragmentImpl.java","files/FruitFragmentImpl.java")
--

[step]
== Querying with Querydsl
--
displayContent("Querydsl Expressions", [{ "file": "files/findAllQueryDslFunc.asciidoc" }])
--

[step]
== Implement GET-Request in FruitResource
--
changeFile("src/main/java/org/acme/spring/data/jpa/repo/fruit/FruitResource.java", {"placeholder": "return null;", "file": "files/function.txt"})
--
====
Now you can run the application in development mode.
[step]
== Run Application
--
executeCommand("devon mvn compile quarkus:dev", "devon mvn compile quarkus:dev", "quarkus.http.host=0.0.0.0")
--

Accessing the application with the following link will send a GET-request for fruits named Cherry. The `FruitResource` will call the `FindByName` method and pass the `name` parameter to the `FruitRepository`'s `findAllQueryDslName` method, which it inherents from the `FruitFragment` interface. The querying occurs in the method's implementation, as explained in step 6.
https://[[HOST_SUBDOMAIN]]-8080-[[KATACODA_HOST]].environments.katacoda.com/fruits/name/Cherry
====

====
== Conclusion
To summarize, we learned how to integrate Querydsl into your Maven project and querying with Querydsl. For more information on queries, visit the Querydsl link:https://querydsl.com/static/querydsl/latest/reference/html_single/[documentation]
====