【问题标题】:jOOQ: set where condition before the select statementjOOQ:在 select 语句之前设置 where 条件
【发布时间】:2020-05-20 23:31:48
【问题描述】:

我有这个 jOOQ 选择,根据参数值,where 条件应该等于或不等于一个值:

如果参数 = true:

    Charts c = CHARTS.as("c");
    context.select()
                .from(c)
                .where(c.CHART_TYPE.eq(100))  // note the eq
                .orderBy(c.NAME)
                .fetch();

如果参数 = 假:

    Charts c = CHARTS.as("c");
    context.select()
                .from(c)
                .where(c.CHART_TYPE.ne(100))  // note the ne
                .orderBy(c.NAME)
                .fetch();

我不想重复整个选择(在许多情况下比示例更复杂/更长)。有没有办法只根据参数设置where条件,然后插入到select中?

【问题讨论】:

    标签: java jooq


    【解决方案1】:

    是的,这不是问题,您可以创建一个返回 Condition 对象的方法。

    例如

    Charts c = CHARTS.as("c");
    context.select()
                .from(c)
                .where(createCondtion(c))  
                .orderBy(c.NAME)
                .fetch();
    
    private Condition createCondition(Charts c) {
       if (parameter == false) {
          return c.CHART_TYPE.ne(100);
       } else {
          return c.CHART_TYPE.eq(100);
       }
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用Field.compare(Comparator, T)

      context.select()
             .from(c)
             .where(c.CHART_TYPE.compare(parameter ? Comparator.EQ : Comparator.NE, 100))
             .orderBy(c.NAME)
             .fetch();
      

      【讨论】:

        猜你喜欢
        • 2012-01-26
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        相关资源
        最近更新 更多