我正在尝试在 jOOQ 中为 Postgres 执行 upsert 风格的语句。我运行的框架负责处理这种特定情况下的并发问题,因此我并不担心这一点。我仅使用 jOOQ 来创建 SQL,实际执行是通过 Spring 的 JdbcTemplate 和 BeanPropertySqlParameterSource 完成的。
我决定采用两步“插入..不存在的地方”/“更新..”过程。
我的SQL是:
insert into mytable (my_id, col1, col2) select :myId,
:firstCol, :secondCol where not exists (select 1
from mytable where my_id = :myId)
Run Code Online (Sandbox Code Playgroud)
我正在使用 Postgres 9.4、jOOQ 3.5。我不知道如何表达 select 中的 jOOQ 参数和 jOOQ 中的“where not办法”子句。
更改编程语言或数据库的建议在我的情况下不可行。
如果您想在 jOOQ 中重用命名参数,理想情况下,您可以在查询外部创建 AST 元素,如下所示:
// Assuming a static import
import static org.jooq.impl.DSL.*;
Param<Integer> myId = param("myId", Integer.class);
Run Code Online (Sandbox Code Playgroud)
然后您可以在查询中多次使用它:
using(configuration)
.insertInto(MY_TABLE, MY_TABLE.MY_ID, MY_TABLE.COL1, MY_TABLE.COL2)
.select(
select(
myId,
param("firstCol", MY_TABLE.COL1.getType()),
param("secondCol", MY_TABLE.COL2.getType())
)
.whereNotExists(
selectOne()
.from(MY_TABLE)
.where(MY_TABLE.MY_ID.eq(myId))
)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4106 次 |
| 最近记录: |