简体   繁体   English

如何在JOOQ中添加多个字段以选择语句?

[英]How add multiple fields to select statement in JOOQ?

I'm trying to add fields to select after the first initialization. 我正在尝试添加字段以便在首次初始化后进行选择。 It seems that there is no way to do it as it just recreates one. 似乎没有办法做到,因为它只是重新创建一个。

String select = "actor_id,first_name,last_name,last_update";
DSLContext context = DSL.using(SQLDialect.DEFAULT);
Select select = context.select();
for (String field : select.split(",")) {
    select = context.select(field(name(field)));
}
System.out.println(select.getSQL());
// The value is always SELECT last_update ... 
// But I need select actor_id,first_name,last_name,last_update ...

I don't see a way to keep the select and then add WHERE, LIMIT etc as subsequent steps as and when required in the code flow. 我没有办法保留选择,然后在代码流中需要时在随后的步骤中添加WHERE,LIMIT等。 Should everything be done in the same step? 一切应该在同一步骤中完成吗?

Something like: 就像是:

select = select("test");
// code
// code
select = select("another field");
// code
// And add other sql statements to the DSL and finally get the sQL

in the snippet you've provided, the value of select is always "last_update" because the for-loop re-assigns select on each iteration. 在您提供的代码段中, select的值始终为“ last_update”,因为for循环在每次迭代时都会重新分配select the last evaluated value is "last_update", so naturally, that's what select ends up being. 最后一个评估值是“ last_update”,因此, select自然是这样。

here's an approach that initializes the Select with the full range of columns to select, rather than building it up field-by-field: 这是一种使用要Select的全部列来初始化Select的方法,而不是逐字段构建它:

final List<Field<?>> projection = new ArrayList<Field<?>>();

final String columnNames = "actor_id,first_name,last_name,last_update";

for(String columnName : columnNames.split(",")) {
    projection.add(field(name("Tblactor", columnName)));
}

Select query = context.select(projection);
...

hope that helps! 希望有帮助!

While hsl's answer shows a much better approach of storing the entire projection in a local variable, I'll just briefly comment on the mistake you made, which is simple: 虽然hsl的答案显示了将整个投影存储在局部变量中的更好的方法,但我只是简单地评论一下您犯的错误,这很简单:

SelectSelectStep select = context.select();
for (String field : select.split(",")) {

    // Your code: This always creates a new select statement from scratch
    // select = context.select(field(name(field)));

    // The code you meant to write
    select = select.select(field(name(field)));
}

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

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