在 jOOQ 中动态创建条件

huangapple go评论75阅读模式
英文:

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&lt;?&gt; table, int x, int y, int sk) {
    Field&lt;Integer&gt; skField = table.field(&quot;sk&quot;, int.class);
    return x &gt; y ? skField.eq(sk) : skField.eq(0);
}

or a more verbose, but type safe version:

public static &lt;R extends Record&gt; Condition makeCondition(
        Table&lt;R&gt; table,
        TableField&lt;R, Integer&gt; skField,
        int x,
        int y,
        int sk) {
    return x &gt; y ? skField.eq(sk) : skField.eq(0);
}

// usage:
var c = makeConditon(FORMULAS, FORMULAS.SK, 1, 2, 3);

huangapple
  • 本文由 发表于 2020年8月28日 04:11:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63623525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定