根据可以为空的参数构建 Hibernate 查询

Building Hibernate query depending of parameters that can be nulls

所以我现在正在做一个项目 第一次使用 Hibernate 在这个项目中我也在使用 Swing 我有一个包含多个 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();

 }

如您所见,我正在测试要将它们添加到查询中的值。 我的问题是有没有办法添加这些值? 因为查询 +="" 不工作。

您应该考虑使用 Criteria。在处理多个 where 语句时更干净。

例如

Criteria cr = session.createCriteria(YourEntityClass.class);
cr.add(Restrictions.eq("property1", value1));
cr.add(Restrictions.eq("property2", value2));
List results = cr.list();

看看这些例子here

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.

以上是我的评论,我决定向您展示这段代码。

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

现在你可以简单地写:

//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 + "'"; }

它更具可读性,因此在将来出现错误时更容易调试。

请看一下DRY原则并遵循它。如果您的问题需要检查相同条件 4 或 5 次(2 次应该足以使用 DRY),请考虑编写一个函数。以人性化的方式称呼它,而不是不同逻辑语句的组合。

干燥。不要重复自己。

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

Wikipedia article about DRY