简体   繁体   English

如何使用JOOQ Model API从基于字符串的列名添加动态条件?

[英]How to use JOOQ Model API to add dynamic Conditions from String based column names?

I am using the JOOQ Model API to dynamically build a query. 我正在使用JOOQ Model API动态构建查询。 It is similar to what is being asked here : 它类似于这里要求的内容:

However, I need this query to have dynamic conditions based on columns names and values I am passing in as Strings. 但是,我需要此查询具有基于我作为字符串传递的列名称和值的动态条件。 I know in my repository what the table is from a private getTable() method. 我在我的存储库中知道该表来自私有getTable()方法。

String fieldName = "my_column";
String fieldValue = "searchTerm";

SelectQuery<Record> query = create.selectQuery();
query.addFrom(getTable());

Instead of doing something like this... 而不是做这样的事情......

query.addConditions(BOOK.TITLE.like(fieldValue + "%")); 

I need a generalized way to get table fields by name... 我需要一种通用的方法来获取名称的表字段...

query.addConditions(getTable().getTableField(fieldName).like(fieldValue + "%"));

I couldn't find anything on the generated table or record classes that did this. 我在生成的表或记录类上找不到任何内容。 The table class has the TableField static members I need to use, but no way to look them up by name. 表类有我需要使用的TableField静态成员,但无法按名称查找它们。 Is there something else available I am missing? 还有其他可用的东西吗?

If not, I see two courses of action. 如果没有,我会看到两个行动方案。 I prefer the first: 我更喜欢第一个:

  1. Customize the generator somehow to create some kind of internal lookup on the generated Table class. 以某种方式自定义生成器以在生成的Table类上创建某种内部查找。

  2. I could create new TableFieldImpl instances, but that seems like a waste when generated TableImpl classes already have them and I would need to know everything about the table column in order to create it properly. 我可以创建新的TableFieldImpl实例,但是当生成的TableImpl类已经拥有它们时,这似乎是浪费,我需要知道有关表列的所有内容才能正确创建它。

EDIT: I think what I want may be DSL.condition() which can take a SQL string and bound parameters or you can create a condition like this: 编辑:我认为我想要的可能是DSL.condition() ,它可以采取SQL字符串和绑定参数,或者您可以创建这样的条件:

query.addConditions(DSL.condition("? = ?", fieldName,fieldValue));

The method you're looking for is called TableLike.field(String) and it is thus present on all table expressions in the jOOQ API. 您正在寻找的方法称为TableLike.field(String) ,因此它存在于jOOQ API中的所有表表达式中。 For instance: 例如:

query.addConditions(getTable().field(fieldName).like(fieldValue + "%"));

Now, this won't work out of the box, because the Field<?> reference's wildcard will prevent you from comparing that Field with fieldValue + "%" . 现在,这不会开箱即用,因为Field<?>引用的通配符将阻止您将该FieldfieldValue + "%"进行比较。 You have these options: 你有这些选择:

jOOQ 3.5 and less jOOQ 3.5及更低

getTable().field(fieldName).coerce(String.class).like(fieldValue + "%")
((Field<String>) getTable().field(fieldName)).like(fieldValue + "%")

jOOQ 3.6 jOOQ 3.6

getTable().field(fieldName, String.class).like(fieldValue + "%")

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

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