I am writing back-end for renting flat web app and I have no idea how to filter flats from database (ex. rooms available, beds,floor or city). So I have 10 fields , so user can choose all of them in one search to filter flats and I just to wanted put in JPA repository all fields in one method but when I used only 5 of them it started freezing I couldn't add more fields.When I start to type for example NumberOfRooms it's just froze ,then by typing each letter also freezing.
1.Is there any limit for searching(filtering) fields ?
2.What is another way to do that?( I wanted to put everything in one method and in controller check if user used all filters or not, checking each field for null)
List<Flat> findAllByPriceBetweenAndCityAndRentORbuyAndUtilitiesBetweenAndNumberOfBedsBetweenAndNum(FastMoney less,FastMoney greater,String city,Boolean rentORbuy,int util1,int util2,int num1,int num2);
Why would you write an 88-character method that's impossible to parse when you can write a nicely formatted multiline JPQL query, using Text Blocks
for extra points?
If you want to build the query dynamically, use Criteria API. You can even benefit from the type-safe Metamodel
.
So, here's what you need to do:
findFlats
method.findFlats
method use Criteria API to build the query dynamically.That's it!
Here, since your user does not always provide all fields you need to use more Dynamic queries. I recommend Specifications as the best way to achieve it.
You can find more info in official documentation: https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
Maybe, rather than having a "find" method with an endless name (even if it is supported) I'd suggest, to improve the readability, to create a custom query. In addition if you want to speed the performance, you can even populate a DTO from the query in order to avoid mappings from your Jpa Entity to the DTO (basically I'm suggesting to use a Projection)
Check how to do it here https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With