To oversimplify the problem: we have a class/table Wine (table "wines") which has, among other attributes:
- name: String
- description: String
- origin: Origin
... where Origin is another class (with table "origins") with just region: String
and country: String
.
What I'm trying to make is a search method in my repository for the RestController to use.
The method declaration in the RestController is like this:
@GetMapping("/search")
public Wine searchProduct(
@RequestParam Optional<String> searchTerm,
@RequestParam Optional<Origin> origin) {
// ???
}
What I'm trying to do now is the following: creating a query for the database where the searchTerm is used if given, same with origin. And it should be pageable. Example:
SELECT * FROM wines JOIN origins ON wines.origin_id = origins.id
WHERE (name LIKE $searchTerm OR description LIKE $searchTerm) AND (/*origin check*/)
If no search term is given, the whole "() AND" part should not be in the query. If no Origin is given... you get it.
Things I've tried:
(Naively) building a massive query in my repository (implements CrudRepository) like here.
Page<Wine> findWinesByNameLikeOrDescriptionLikeAndOriginEquals(..., Pageable pageable);
- Which (apart from being super ugly, especially for more attributes) probably doesn't work because:
- It's not defined whether OR or AND are more important (no brackets).
- No idea whether I can just shove an "Origins" object in there for it to work.
- No idea whether Pageable even works if that's a custom method.
- Which (apart from being super ugly, especially for more attributes) probably doesn't work because:
Using "Specifications and Querydsl" as suggested by spring.io here.
- Which I'm just to stupid to understand, especially with those Q classes at the bottom of the post or the _ classes in the beginning. It just seems way too compicated for what it should do.
- Also there are no pagination options. There is, however, a possible fix like here but I didn't get to it since using those _ and/or Q classes was to much of an overhead to start with.
Also this is just an example I found from 2013 which I don't even understand in general but kinda looks like it would be very fitting.