Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter an entity by multiple fields using a Spring JPA Repository?

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);
like image 899
Danik Avatar asked Sep 16 '20 11:09

Danik


Video Answer


3 Answers

88-character query method? Please, don't!

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?

Custom Implementations for Spring Data Repositories to the rescue!

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:

  1. Go to the Custom Implementations for Spring Data Repositories section in the Spring Data manual and see how to create a custom repository where you will add the findFlats method.
  2. Inside the new findFlats method use Criteria API to build the query dynamically.

That's it!

like image 90
Vlad Mihalcea Avatar answered Oct 22 '22 12:10

Vlad Mihalcea


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/

like image 10
Viktar Patotski Avatar answered Oct 22 '22 13:10

Viktar Patotski


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/

like image 2
geeksusma Avatar answered Oct 22 '22 12:10

geeksusma