javastringnullstring-utils

Building Hibernate query depending of parameters that can be nulls


so i am working on a project right now 1st time using Hibernate in this projet i am using Swing too i have a form with multiple jTextFields

 public List<Object[]> getoperations(String a,String c,String n,String e,String d) {
     SessionDao s=new SessionDao();
     session=s.getSession();
     Query q;
     q=session.createQuery("select idTiers,beneficiaire,emetteur,montant,numcompte,t_param_nature_operation.libelleNature,dateValidite,dateCreation where");
     if (a != null && !a.isEmpty()) { q+= " and codeBanque='" + a + "'"; }
     if (c != null && !c.isEmpty()) { q += " and numCompte='" + c + "'"; }
     if (n != null && !n.isEmpty()) { q += " and t_param_nature_operation_.libelleNature='" + n + "'"; }
     if (e != null && !e.isEmpty()) { q += " and decision='" + e + "'"; }
     if (d != null && !d.isEmpty()) { q += " and dateCreation='" + d + "'"; }

    q+= " order by idTiers" ;
     return q.list();

 }

As you see I am making a test on the values to add them in the query. My question is there a way to add those values? since query +="" isn't working.


Solution

  • Personally, I would add Guava utils to my project and use isNotBlank() function. Anyway, you can write your own static function that would return true if not null and not empty and false otherwise, and later use it. It'll make your code much clearer.

    The above was my comment and I decided to show you this little piece of code.

    public static boolean isBlank(String s) {
        if (s == null)
            return true;
        if (s.isEmpty())
            return true;
        return false;
    }
    

    Now you can simply write:

    //static import your isBlank() method
    //import static package.classInWhichIsBlankIsDeclared;
    
     if (!isBlank(a) { q+= " and codeBanque='" + a + "'"; }
     if (!isBlank(b) { q+= " and codeBanque='" + b + "'"; }
     if (!isBlank(c) { q+= " and codeBanque='" + c + "'"; }
     if (!isBlank(d) { q+= " and codeBanque='" + d + "'"; }
    

    It's much more readable so it'll be much easier to debug in case of errors in the future.

    Please, have a look at DRY principle and follow it. If your issue require checking same condition 4 or 5 times (2 times should be enough to use DRY) consider writing a function. call it the way that it'll be human-friendly instead of combination of different logical statements.

    DRY. Don't Repeat Yourself.

    "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system"

    Wikipedia article about DRY