Results 1 to 3 of 3

Thread: Query string - Depending on passed values

  1. #1
    Join Date
    Apr 2005
    Posts
    9

    Default 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. #2
    Join Date
    Jun 2005
    Posts
    19

    Default

    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:

  3. #3
    Join Date
    Jan 2005
    Location
    Bucharest, Romania
    Posts
    5,403

    Default

    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 ";
    Costin Leau
    SpringSource - http://www.SpringSource.com- Spring Training, Consulting, and Support - "From the Source"
    http://twitter.com/costinl
    Please use [ c o d e ] [ / c o d e ] tags

Similar Threads

  1. LDAPPasswordAuthenticationDao problem
    By benoit_m35 in forum Security
    Replies: 15
    Last Post: Jan 11th, 2006, 07:04 AM
  2. hibernate pagination
    By oliverchua in forum Data
    Replies: 8
    Last Post: Sep 23rd, 2005, 06:06 PM
  3. Replies: 8
    Last Post: Jul 13th, 2005, 11:20 AM
  4. Replies: 2
    Last Post: May 5th, 2005, 09:35 PM
  5. Enlisting Custom DataSource with JTa
    By shaby775 in forum Data
    Replies: 11
    Last Post: Sep 9th, 2004, 03:00 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •