title: Hibernate query building based on conditions
body: <p>I have a form where user can select search criteria. </p>
  
  <p>The criterias are say:</p>
  
  <pre><code>Product Name: Input field
  Name Option: Radio button group - begins with (default selected)/ is/ contains
  Country: dropdown of country
  Status: All, Active, Blocked
  Type: All, One, Two, Three
  </code></pre>
  
  <p>Only Product Name is mandatory. Other dropdowns are optional. </p>
  
  <p>So if country is not given, I should find products for all countries.
  If active is not given, I should find both active and blocked products.
  If Type is not given, I should return all the three types products.</p>
  
  <p>I am building hibernate query as below:</p>
  
  <pre><code>String productName = searchCriteria.getValue("productName");
  String productNameCriteria = searchCriteria.getValue("productNameCriteria");
  String country = searchCriteria.getValue("country");
  String status = searchCriteria.getValue("status");
  String type = searchCriteria.getValue("type");
  
  Query prodQuery = null;
  String prodSql = "select count(*) from Product p where";
  
  // is
  if (productNameCriteria.equalsIgnoreCase("IS")){
              prodSql += "p.productName = '"+productName+"'";
          }
  
  // begins with
  else if (productNameCriteria.equalsIgnoreCase("BEGINS WITH")){
              prodSql += "p.productName = '"+productName+"%'";
          }
  
  // contains
  else (productNameCriteria.equalsIgnoreCase("BEGINS WITH")){
              prodSql += "p.productName = '%"+productName+"%'";
  
          }
  
  if(!country.equalsIgnoreCase("0")){
           prodSql += " and p.country = '"+country+"'";
       }
  
  if(!status.equalsIgnoreCase("ALL")){
        if(status.equalsIgnoreCase("active"))
            prodSql += " and p.status = 'active'";
  
        else
            prodSql += " and p.status = 'blocked'";
   }
  
   if(!type.equalsIgnoreCase("ALL")){
        if(type.equalsIgnoreCase("one"))
            prodSql += " and p.type = 'one'";
  
        else if(type.equalsIgnoreCase("two"))
            prodSql += " and p.type = 'two'";
  
        else 
           prodSql += " and p.type = 'three'";
  }
  
  prodQuery = this.em.createQuery(prodSql);
  List&lt;Object[]&gt; results = prodQuery.getResultList();
  </code></pre>
  
  <p>Am I doing query building the right way ? Or is there any other efficient method ???</p>
  
  <p>Thanks for reading!!    </p>