0

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

 }

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

4

2 回答 2

0

就个人而言,我会将 Guava utils 添加到我的项目中并使用 isNotBlank() 函数。无论如何,您可以编写自己的静态函数,如果不为 null 且不为空,则返回 true,否则返回 false,然后使用它。它会让你的代码更清晰。

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

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)考虑编写一个函数。将其称为对人类友好的方式,而不是不同逻辑语句的组合。

干燥。不要重复自己。

“每条知识都必须在系统中具有单一的、明确的、权威的表示”

维基百科关于 DRY 的文章

于 2016-07-25T08:38:04.423 回答
0

你应该考虑使用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

于 2016-07-24T16:49:52.663 回答