简体   繁体   English

如何使用JOOQ正确构建动态WHERE子句条件?

[英]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: 我需要能够使用String元素列表动态构建JOOQ“ WHERE” close,其中每个元素代表一个文件管理器:

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: 我希望能够将我的filterList转换为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? 将此类过滤器列表转换为JOOQ的WHERE子句的条件的正确语法是什么?

There are many ways in jOOQ to write the kind of dynamic SQL that you're trying to write. jOOQ中有很多方法可以编写您要编写的动态SQL In your particular case, the where(Collection<? extends Condition>) method is the most suitable. 在您的特定情况下, where(Collection<? extends Condition>)方法是最合适的。 And again, you have several options: 同样,您有几种选择:

Write "plain SQL" conditions 编写“普通SQL”条件

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: 您似乎可以解决使用jOOQ的类型更安全的API,甚至使用代码生成器的问题,因此构造filterList的适当方法是:

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? 您已经使用DSL.table(String)创建了一个表引用,那么为什么不还使用DSL.field(String, Class)创建列引用呢?

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 . 您显然不能将List<String>转换为Condition Those types are completely unrelated and the Java compiler cannot "guess" that what you really meant was one of the above type conversions. 这些类型是完全无关的,并且Java编译器无法“猜测”您真正的意思是上述类型转换之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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