gpt4 book ai didi

java-8 - 如何在JOOQ中编写OPTIONAL where子句

转载 作者:行者123 更新时间:2023-12-04 09:58:35 25 4
gpt4 key购买 nike

List<MyTable> result = DSL.using(configuration())
.select()
.from(MY_TABLE)
.where(MY_TABLE.ID1.equal(pk_id1))
.and(MY_TABLE.ID2.equal(fk_id2))
.and(MY_TABLE.ID3.equal(fk_id3))
.orderBy(MY_TABLE.ID.asc())
.limit(limit)
.fetchInto(MY_TABLE)
.map(mapper());

我正在尝试编写一些代码,以允许我的查询采用三个可选ID,例如,我希望查询最终成为
select * from my_table where ID1=5 and ID2=6 and ID3=7 .... etc 

但是,我也希望能够排除任何ID的选项
select * from my_table where ID2=6 and ID3=7 

或者
select * from my_table where ID3=7

问题在于,第一个“where”子句属于id one,其余的属于ands,因此如果我执行if语句并删除了where,那么我将只剩下
List<MyTable> result = DSL.using(configuration())
.select()
.from(MY_TABLE)
.and(MY_TABLE.ID2.equal(fk_id2))
.and(MY_TABLE.ID3.equal(fk_id3))
.orderBy(MY_TABLE.ID.asc())
.limit(limit)
.fetchInto(MY_TABLE)
.map(mapper());

而且它行不通。

我试图寻找类似 where id = *的东西,其中*本质上没有过滤器,但是我找不到类似的东西。

最佳答案

jOOQ使编写SQL的感觉就像是静态的嵌入式SQL。但事实并非如此。每个jOOQ查询都是由表达式树组成的动态SQL查询-您只是没有注意到它。
SelectWhereStep.where(Condition) 方法采用Condition参数,您不必将其与WHERE子句放在一起。您可以在查询之前构造它:

Condition condition = DSL.noCondition(); // Alternatively, use trueCondition()
if (something)
condition = condition.and(MY_TABLE.ID1.equal(pk_id1));
if (somethingElse)
condition = condition.and(MY_TABLE.ID2.equal(fk_id2));
if (somethingOther)
condition = condition.and(MY_TABLE.ID3.equal(fk_id3));
您现在可以将其传递给查询:
List<MyTable> result = 
DSL.using(configuration())
.select()
.from(MY_TABLE)
.where(condition)
.orderBy(MY_TABLE.ID.asc())
.limit(limit)
.fetchInto(MY_TABLE)
.map(mapper());
DSL中还有一些实用程序方法,例如:
  • DSL.condition(Map<Field<?>,?>) 从字段/值比较图
  • 构造条件
  • DSL.condition(Record) 用于使用Query By Example模式
  • DSL.condition(Operator, Condition...) 或简单地说是 DSL.and(Condition...) ,用于从数组(或集合)
  • 构造 AND连接条件

    手册中也对此进行了记录: http://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql/
    注意,通常不需要直接引用 XYZStep类型。 You should mostly be able to write dynamic SQL through more elegant ways, as I've shown in this blog post

    关于java-8 - 如何在JOOQ中编写OPTIONAL where子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37238418/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com