Search code examples
javajooq

jOOQ: set where condition before the select statement


I have this jOOQ select that depending on a parameter value the where condition should be either equal or not equal to a value:

if parameter = true:

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

if parameter = false:

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

I don't want to repeat the entire select (in many cases is more complex/longer than the example). Is there a way to only set the where condition depending on a parameter and then insert it into the select?


Solution

  • Yes that's not a problem you can create a method that returns a Condition object.

    For example

    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);
       }
    }