ps0604
ps0604

Reputation: 1071

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?

Upvotes: 1

Views: 838

Answers (2)

Lukas Eder
Lukas Eder

Reputation: 220762

You could use Field.compare(Comparator, T)

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

Upvotes: 1

Simon Martinelli
Simon Martinelli

Reputation: 36103

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

Upvotes: 2

Related Questions