0

I'm using Java, Spring Boot and PostgreSQL
Right now I'm trying to send request form with multiple paramaters from website, to search the database for rows that match these parameters.

Like that

http://localhost:8080/search?vtitle=&vcompany=Epam&vcity=Kiev&vlanguage=Java

I already figured out how to get such a solid query, but there is a problem.

List<JobSite> allJobs = jobRepository.findByTitleContainingAndCompanyAndCityAndLanguage(searchForm.getVtitle(),
            searchForm.getVcompany(),
            searchForm.getVcity(),
            searchForm.getVlanguage());

    allJobs.sort(Comparator.comparing(JobSite::getTime).reversed());
    model.addAttribute("jobs", allJobs);
    return "index";

If i will not select one of the parameters it will not query this rows because of how findBy... method works.

If i will change code a little to

public String submit(@RequestParam MultiValueMap<String, String> params, Model model) {

I will get some freedom. But even so I can't find a way to "automatically generate" queries like

SELECT * FROM table WHERE title = 1 AND company = 1 AND city = 1 AND language = 1 
SELECT * FROM table WHERE company = 1 AND city = 1 AND language = 1 
SELECT * FROM table WHERE city = 1 AND language = 1 
SELECT * FROM table WHERE language = 1 
SELECT * FROM table WHERE title = 1 AND city = 1 AND language = 1 

And so on.

If I will code it myself with Spring it will become a mess.

What is the best way to do such a search from site?

chrisb2244
  • 2,940
  • 22
  • 44
Warp
  • 37
  • 1
  • 7
  • I just thought that i can create String and do something like that `String query = " SELECT * FROM table WHERE "; If (title != null) { query += "title = " + object.getTitle; } If (company != null) { query += "company = " + object.getCompany; } ` Is it a right way? – Warp Nov 16 '17 at 14:55
  • Possible duplicate of [Multi-Column Search with Spring JPA Specifications](https://stackoverflow.com/questions/46970689/multi-column-search-with-spring-jpa-specifications) – Alan Hay Nov 17 '17 at 10:49

1 Answers1

0

In this case you can use Spring Data JPA Specifications. It's little bit tricky, refer these links you get an idea

1 . Spring Data JPA Specifications

  1. advanced-spring-data-jpa-specifications
Satish Kr
  • 590
  • 5
  • 12
  • I didn't find a solution to my problem there. I still have to write a bunch of code that will be repeated. – Warp Nov 17 '17 at 08:11