I have a form in Angular which looks like so
The user can input only the field he wants and I send the form to Spring Rest API like so
{
"symbol": "DOL",
"currency": "CAD"
}
From there how to redirect the JPA repository query. I mean if the user only select symbol then the query will be findAllBySymbol ; if the user select the symbol AND the currency then the query should be findAllBySymbolAndCurrency.
How to approach this? Should I query all and filter out? That does not sound optimal
2
Answers
A bit more details with regards to the dependency required for Maven
You can achieve that using specifications.
In order to do that, first extend your repository with the
SpecificationExecutor
In order to easily work with the specifications, it’s advised to add the `jpa-modelgen’ dependency:
(for gradle groovy)
Then, define the specifications that will be used for the search:
Once that’s configured, you can start using the repository by using i.e.
findAll
orfindOne
methods:In the example null is checked within the specification, so that if the symbol is
null
(not provided), all the results are returned. This should be adapted to your needs.In order to explore the specifications in more details, check out the spring docs https://docs.spring.io/spring-data/jpa/reference/jpa/specifications.html, as well as jpa criteria API https://openjpa.apache.org/builds/3.2.2/apache-openjpa/docs/#jpa_overview_criteria