[java, spring, jpa, jpql]
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.
active properties to our
Restaurant entity. You can see how on this commit.
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.
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!
That's the exact scenario to use a JPQL query. Let's refactor the code above:
- Rename the method to something more acceptable, like
- Add the annotation
@Queryabove 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
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 working app is here (wait for Heroku to load the app, it takes a few seconds on the free tier).