简体   繁体   中英

How to properly build dynamic WHERE clause conditions with JOOQ?

I need to be able to dynamically build JOOQ "WHERE" close, using a list of String element, where each element represents a single filer:

List<String> filerList = new ArrayList<>();
    filerList.add("column1=Y");
    filerList.add("column2=Z");

The desired end-result should look like this:

  String sql =
    DSL.select(flds)
            .from(table(tableName))
            .where(conditions)
            .getSQL();

I was hoping to be able to cast my filterList into Condition:

    Collection<Condition> conditions = new ArrayList<Condition>();
    conditions.add((Condition) filerList);

But this cast fails.

What is the proper syntax to turn such a filter list into a Condition for JOOQ's WHERE clause?

There are many ways in jOOQ to write the kind of dynamic SQL that you're trying to write. In your particular case, the where(Collection<? extends Condition>) method is the most suitable. And again, you have several options:

Write "plain SQL" conditions

You seem to work around using jOOQ's more type safe APIs, or even the code generator, so the appropriate way to construct your filterList is this:

List<Condition> filterList = new ArrayList<>();
filterList.add(condition("column1=Y"));
filterList.add(condition("column2=Z"));

The below static import is assumed to be present:

 import static org.jooq.impl.DSL.*;

Create actual field references

You've created a table reference using DSL.table(String) , so why not also create column references using DSL.field(String, Class) , for instance?

List<Condition> filterList = new ArrayList<>();
filterList.add(field("column1", String.class).eq(y));
filterList.add(field("column2", Integer.class).eq(z));

Using the code generator

Of course, this would be even more powerful and simple, if you would be using the code generator.

Why your cast didn't work

You obviously cannot cast a List<String> to a Condition . Those types are completely unrelated and the Java compiler cannot "guess" that what you really meant was one of the above type conversions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM