【问题标题】:How do I dynamically include expressions in Ebean queries?如何在 Ebean 查询中动态包含表达式?
【发布时间】:2016-09-13 18:45:26
【问题描述】:

我有一个搜索应用程序,其中许多条件组合成一个“和”“或”列表。

根据用户输入,其中一些可以为 null,如果它们为 null,则不应考虑这些值。

示例:

 public static PagedList<Profile> exampleForSO(String param1, String params2, Integer number, Double d, Boolean condition1, Boolean condition2) {

        return find.where().ieq("param1", param1).
                ieq("param2", params2).
                eq("number", number).
                // based on the fact if condition1 is null include an eq("condition", condition1); block
                // based on the fact if condition2 is null include an eq("condition", condition1); block
            // if param1.equals("test") create an expression .eq("param1", param1).

        findPagedList();
    }

我可能可以用几个 if else 块来解决这个问题,并根据该标准返回结果,但是有超过 12 种不同的条件,因此如果它们为空,那么一种可靠的方法来排除它们会很棒。

我还可以创建许多不同的方法,但必须有一些更聪明的方法。

此外,条件不必为空,但可以有一些特定值使它们在查询中过时,例如:

params1.equals("something"); 

不要包含它,因为“某事”无论如何都不会改变搜索结果。

有什么建议吗?

【问题讨论】:

  • 看看这个post
  • @Sivakumar,谢谢你,这就是我要找的。​​span>

标签: playframework ebean


【解决方案1】:

您可以使用 find.where() 返回的对象 ExpressionList 并动态添加条件。

例如:

        ExpressionList<Profile> expressionList =  find.where();
        expressionList.ieq("param1", param1);
        expressionList.eq("param2", param2);
        if(condition1){
           expressionList.eq("...", ...);
        }
        if(condition2){
           expressionList.ieq("...", ...);
        }

最好的问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多