Using JPQL with Spring Data JPA
[java, spring, jpa, jpql]
You'll have a better experience reading in DEV
Click here to continue reading this post there >>
However, if you want to know more about the project to mirror my posts from DEV here (and why), go ahead and read more.
You can continue to read here too, it's up to you... =]
This is the post #4 of the series "Querying your Spring Data JPA Repository".
Let's recap: by now you should have an app like this. The frontend (Thymeleaf + a very bad UI design) doesn't matter since our goal is to understand several ways to query your Spring Data JPA repository. Regardless, I added Bootstrap to make make it easier on the eyes.
Adding a few properties
Let's add city
, grabAndGo
and active
properties to our Restaurant
entity. You can see how on this commit.
The requirement
Let's say now that you want to create a new custom search on our awesome search area:
This searches for active restaurants with Grab'n'Go enabled in a city specified by the user.
"I know how to do this already"
Yes, if you're following the series you already know how to do this with Query Methods. Here you go:
- Create a new method on the RestaurantRepository interface:
List<Restaurant> findAllByActiveTrueAndGrabngoTrueAndCityContaining(String city);
That's going to work, but look at the size of the method name! C'mon! Imagine having to use this huge method name all over your code. That's not clean!
@Query
to the rescue
That's the exact scenario to use a JPQL query. Let's refactor the code above:
- Rename the method to something more acceptable, like
activeGrabngoByCity
. - Add the annotation
@Query
above the method name. - Create your custom JPQL query.
Here's the result:
@Query("from Restaurant r where r.active = true and r.grabngo = true and r.city like %:city%")
List<Restaurant> activeGrabngoByCity(String city);
Notice that you don't have to follow the Query Methods' rules to name the method. You're telling Spring that you're providing the query for this method via the @Query
annotation.
For now that's all that I'm going to cover. You can take a look at this documentation from Hibernate to do your own cool stuff, JPQL is very powerful!
The example app
The working app is here (wait for Heroku to load the app, it takes a few seconds on the free tier).
Commits related to this post
Adds Bootstrap: 020142.
Adds new properties to the Restaurant: ab7a2e.
Refactors to JPQL: 8758bf.
brunodrugowick / jpa-queries-blog-post
A demo project for a blog post about (Spring Data) JPA.
…