英文:
Creating a condition dynamically in jOOQ
问题
我有以下两行jOOQ代码,这段代码正常工作:
Formulas f = FORMULAS.as("f");
Condition condition = x > y ? f.SK.eq(sk) : f.SK.eq(0);
现在,因为我有100个需要相同条件的表,而且条件比上面的示例复杂得多,我想创建一个如下的方法:
public Condition getCondition(Table table, int x, int y, int sk) {
Condition condition = // 在这里编写一个通用的条件
return condition;
}
但是我不知道如何通用地将列分配给表。如何解决这个问题?
英文:
I have the following two jOOQ lines, this works fine:
Formulas f = FORMULAS.as("f");
Condition condition = x > y ? f.SK.eq(sk) : f.SK.eq(0);
Now, since I have 100 tables that need the same condition and the condition is much more complex than the example above, I would like to create a method like so:
public Condition getCondition(Table table, int x, int y, int sk) {
Condition condition = // write here a generic condition
return condition;
}
But I don't know how to generically assign a column to a table. How to approach this?
答案1
得分: 3
你可以使用以下代码:
public static Condition makeCondition(Table<?> table, int x, int y, int sk) {
Field<Integer> skField = table.field("sk", int.class);
return x > y ? skField.eq(sk) : skField.eq(0);
}
或者更详细但类型安全的版本:
public static <R extends Record> Condition makeCondition(
Table<R> table,
TableField<R, Integer> skField,
int x,
int y,
int sk) {
return x > y ? skField.eq(sk) : skField.eq(0);
}
// 使用方式:
var c = makeCondition(FORMULAS, FORMULAS.SK, 1, 2, 3);
英文:
You can use the following:
public static Condition makeCondition(Table<?> table, int x, int y, int sk) {
Field<Integer> skField = table.field("sk", int.class);
return x > y ? skField.eq(sk) : skField.eq(0);
}
or a more verbose, but type safe version:
public static <R extends Record> Condition makeCondition(
Table<R> table,
TableField<R, Integer> skField,
int x,
int y,
int sk) {
return x > y ? skField.eq(sk) : skField.eq(0);
}
// usage:
var c = makeConditon(FORMULAS, FORMULAS.SK, 1, 2, 3);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论