Announcement Announcement Module
Collapse
No announcement yet.
Query string - Depending on passed values Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Query string - Depending on passed values

    Hi,

    I've got a function like this:

    Code:
    public List getList(String a, String a, Date c) {
    		String query = "from de.model.sap.Table1 t1 where t1.col1 = ? and t1.col2 = ? and t1.col3 = ?";
    	String obj[] = new String[3];
    	obj[0] = a;
            obj[0] = b;
            obj[0] = c;
    	return this.getHibernateTemplate().find(query, obj);
    }
    Now I want my string a little bit more dynamic. If a passed value is null, it should't be considered in the query.

    For example, if String a is null the query string only be:

    "from de.model.sap.Table1 t1 where t1.col2 = ? and t1.col3 = ?"


    Is there a way (or whatever) to achieve this, NOT creating this query/string by hand in a way like this:

    Code:
    if(a=! null || b!= null || c != null){
    	query += " WHERE ";
    }
    ...


    Thanks
    Jonny

  • #2
    Use the criteria query api instead:

    Code:
    final Criteria criteria = session.createCriteria(Table1.class);
    if (a != null) criteria.add(Restrictions.eq("col1", a);
    if (b != null) criteria.add(Restrictions.eq("col2", b);
    if (c != null) criteria.add(Restrictions.eq("col3", c);
    final List list = criteria.list();
    String concatenated queries are evil!

    :evil:

    Comment


    • #3
      Null values are a special case - you have to add an if and create the query based on these values:
      Code:
      if (a != null)
         query += " t1.col1 = ? ";
      else
         query += " t1.col1  is null ";

      Comment

      Working...
      X