Spring-MVC, Hibernate, Postgres : Searching in database with multiple variables


I am working on a Spring-MVC application in which I would like to search in the database for a combination of options which the user selects. So let's say that there are 10 options, and if user selects 7 of them, how can I effectively write a single method in DAO with a single query which can adapt to the number of options. Kindly see the image below :

Ebay search

As you can see on the left hand side, there are multiple options and the user can select whichever the user chooses. I am looking for something similar where I have created a Search object entity and this entity I would like to pass to dao, where its variables will be extracted and search executed in database.

But if there are even like 3 variables, I see the query looking as :

Pseudo code :

public ResultObject doSearch(var1, var3, var3){
// hibernate query for search where var1 equals true
//Hibernate query for search where var2 is set by user and var1 is true

But if I keep it doing it in such a horrible fashion, I will never finish. What is the way to handle multiple variables for search when only the ones set should be included and others discarded. Kindly let me know. Thanks.

Use a StringBuilder. As long as the variables are independent from each other this should be easier.

StringBuilder sb = new StringBuilder();

sb.append("FROM phone WHERE 1=1 ");

if (var1) {
    sb.append(" AND var1 = :var1");

if (var2) {
    sb.append(" AND var2 = :var2 ");


This video can help you solving your question :)
By: admin