skip to content

In jOOQ, how do you build a customer search query whose WHERE clause depends on which optional filters were supplied?

level: middleimportance: should knowfreq 50%

answer

  1. conditions are values
  2. Field, Condition, Table types
  3. the no-op condition
  4. where() takes a collection
  5. empty AND is not empty

basics

~20 s

Build each supplied filter as a jOOQ Condition from a generated Field, then combine them with DSL.noCondition() or pass a List<Condition> to where(). Absent filters add nothing, values stay bound, and type errors fail at compile time.

solid answer

~40 s

jOOQ models a query as typed objects: a `Table<R>` such as the generated `CUSTOMER`, `Field<T>` columns such as `CUSTOMER.EMAIL`, and `Condition` predicates produced by field methods like `eq`, `ge` or `containsIgnoreCase`. For optional filters, start from `DSL.noCondition()` and reassign `c = c.and(...)` for each supplied filter, or collect conditions in a list and call `where(conditions)`. `noCondition()` renders nothing, and `where()` with an empty collection adds no `WHERE` at all. The trap is `DSL.and(emptyList)`, which returns `DSL.trueCondition()`, the AND identity, so an always-true predicate appears. `Condition` methods return a new condition rather than mutating, so an unassigned `and()` silently drops that filter. Values passed to `eq` are bound, and a `Field<Integer>` rejects a `String` at compile time.

code

kotlin · 13 lines
kotlin
import org.jooq.Condition
import org.jooq.impl.DSL

import com.example.db.Tables.CUSTOMER

fun customerFilter(country: String?, term: String?): Condition {
    var c: Condition = DSL.noCondition()
    if (country != null) c = c.and(CUSTOMER.COUNTRY.eq(country))
    if (term != null) c = c.and(CUSTOMER.NAME.containsIgnoreCase(term))
    return c
}

val rows = ctx.selectFrom(CUSTOMER).where(customerFilter(null, null)).fetch()

go deeper

for a junior

Recall that Table, Field and Condition are typed objects, and that a condition comes from a field method such as eq.

for a middle

Explain folding from noCondition() or passing a list to where(), and what each renders when no filter applies.

for a senior

Spot the unassigned and() and the DSL.and(emptyList) identity in review, and pin filter shapes with getSQL() tests.

for a principal

Decide where filter-building code lives so every search composes conditions from generated fields rather than strings.

## The building blocks jOOQ represents SQL as typed Java objects rather than strings. - **`Table<R>`**: a table, usually a generated constant such as `CUSTOMER`, whose record type `R` is the generated `CustomerRecord`. - **`Field<T>`**: a column or expression with a Java type, such as `CUSTOMER.EMAIL` (`Field<String>`) or `CUSTOMER.CREATED_AT`. Generated columns are `TableField<R, T>`, a `Field<T>` that knows its table. - **`Condition`**: a predicate. You get one from a field method: `CUSTOMER.COUNTRY.eq(country)`, `CUSTOMER.CREATED_AT.ge(since)`, `CUSTOMER.NAME.containsIgnoreCase(term)`. Because these are ordinary values, a search filter becomes ordinary Java control flow: decide which conditions apply, then hand them to `where()`. The type parameter catches mistakes early, so comparing a `Field<Integer>` with a `String` does not compile. Why an absent filter should add no predicate is a general data-access question; here the interest is jOOQ's API for doing it. ## Two idioms that work **Fold from the no-op condition.** `DSL.noCondition()` is a condition that renders nothing. Combining it with another condition returns the other one, and if every filter is absent, `where(noCondition())` omits the `WHERE` clause entirely. ```java import org.jooq.Condition; import org.jooq.impl.DSL; import static com.example.db.Tables.CUSTOMER; Condition c = DSL.noCondition(); if (filter.country() != null) c = c.and(CUSTOMER.COUNTRY.eq(filter.country())); if (filter.since() != null) c = c.and(CUSTOMER.CREATED_AT.ge(filter.since())); if (filter.term() != null) c = c.and(CUSTOMER.NAME.containsIgnoreCase(filter.term())); var rows = ctx.selectFrom(CUSTOMER).where(c).fetch(); ``` **Collect into a list.** `SelectWhereStep.where(Collection<? extends Condition>)` connects the conditions with `AND`. An empty collection adds no condition, so again no `WHERE` is rendered. ```java var conditions = new java.util.ArrayList<Condition>(); if (filter.country() != null) conditions.add(CUSTOMER.COUNTRY.eq(filter.country())); var rows = ctx.selectFrom(CUSTOMER).where(conditions).fetch(); ``` ## The traps | Code | What it renders when no filter applies | |---|---| | `where(DSL.noCondition())` | No `WHERE` clause | | `where(emptyList)` | No `WHERE` clause | | `where(DSL.and(emptyList))` | An always-true predicate, because `DSL.and` of nothing returns `DSL.trueCondition()` | | `where(DSL.trueCondition())` | An always-true predicate | `DSL.and(Collection)` returns the **identity** of `AND` when the collection is empty, which is `trueCondition()`; `DSL.or` of nothing returns `falseCondition()`. If the list only held `noCondition()` values, the result is `noCondition()`. The difference matters when you want the clause to vanish. `where(Condition...)` with several arguments behaves the same way as the collection form: the arguments are connected with `AND`, and any `noCondition()` among them simply drops out. That makes a compact style possible, where each optional filter is written inline as `country == null ? DSL.noCondition() : CUSTOMER.COUNTRY.eq(country)` and all of them are passed to one `where(...)` call. It reads well for three or four filters; beyond that, a dedicated method that returns the combined `Condition` is easier to test. The second trap is **immutability**. `Condition.and(...)` returns a new condition and leaves the receiver unchanged. Writing `c.and(CUSTOMER.COUNTRY.eq(country));` without assigning the result throws that filter away, and the query quietly returns more rows than intended. ## OR, NOT and reuse The same value semantics cover the other connectives. `Condition.or(...)` and `Condition.not()` return new conditions, and `DSL.or(list)` returns `DSL.falseCondition()` for an empty list, the identity of `OR`. If a filter offers "any of these countries", build the inner `OR` group only when the list is non-empty, then `AND` the group into the outer condition. Because a `Condition` is an immutable value, one filter object can serve several queries: - the page query: `ctx.selectFrom(CUSTOMER).where(c).orderBy(CUSTOMER.NAME).limit(50).fetch()`; - the total for the pager: `ctx.fetchCount(CUSTOMER, c)`; - a quick existence check: `ctx.fetchExists(CUSTOMER, c)`. Building the filter once in a dedicated method keeps the page and the count in agreement, which is a common source of subtle bugs when each query assembles its own predicate. ## Values stay bound Each `eq(value)` wraps the value with `DSL.val`, so with default settings every supplied filter becomes a `?` placeholder. The filter structure changes the statement shape, but user input never becomes SQL text. Choosing a sort column from a request is a separate allow-list concern; in jOOQ it means mapping an accepted key to a generated `Field` and calling `asc()` or `desc()` on it. ## Checklist 1. Build each filter from a generated `Field`, never from a column-name string. 2. Fold with `noCondition()` or pass a list to `where()`. 3. Reassign every `and()` result. 4. Avoid `DSL.and(list)` when an empty list should mean "no clause". 5. Render a few filter combinations with `getSQL()` in a unit test to pin the shapes.

  • In jOOQ, how would you let a caller pick the sort column of this search without accepting SQL text?
    Map each accepted sort key to a generated field, for example a `Map<String, Field<?>>` holding `CUSTOMER.NAME` and `CUSTOMER.CREATED_AT`, then call `field.asc()` or `field.desc()` and pass the result to `orderBy`. An unknown key is rejected before any query is built, and no request string ever reaches the SQL.
  • In jOOQ, what is the difference between DSL.noCondition() and DSL.trueCondition()?
    `noCondition()` is a no-op: combined with another condition it yields the other one, and alone it makes jOOQ omit the clause. `trueCondition()` is a real predicate that always evaluates to true and is rendered into the SQL. Use `noCondition()` as the seed for optional filters.

  • Condition.and() mutates the condition, so the result need not be assigned
  • DSL.and() of an empty list renders no WHERE clause
  • Seeding with DSL.trueCondition() is the same as noCondition()
  • Dynamic jOOQ filters need string building with column names
  • Optional filters force inlined values into the SQL