jOOQ插入到..中,对于Postgres不存在 [英] jOOQ insert into .. where not exists for Postgres
问题描述
我正在尝试为jOOQ中的Postgres做一个upsert风格的声明。我正在使用的框架会在这种特定情况下解决并发问题,因此我对此并不担心。我只使用jOOQ来创建SQL,实际的执行是通过Spring的JdbcTemplate和BeanPropertySqlParameterSource完成的。
I'm attempting to do an upsert-style statement for Postgres in jOOQ. The framework I'm running in takes care of concurrency concerns in this specific situation so I'm not worried about that. I'm only using jOOQ for creating the SQL, the actual execution is done via Spring's JdbcTemplate and a BeanPropertySqlParameterSource.
我决定采用两步操作
我的SQL是:
insert into mytable (my_id, col1, col2) select :myId,
:firstCol, :secondCol where not exists (select 1
from mytable where my_id = :myId)
我正在使用Postgres 9.4,jOOQ 3.5。我不确定如何在select和jOOQ中的不存在子句中同时表示jOOQ参数。
I'm using Postgres 9.4, jOOQ 3.5. I'm not sure how to express both the jOOQ params in the select and the "where not exists" clause in jOOQ.
不建议更改编程语言或数据库在我的情况下不可行。
Suggestions to change programming languages or databases aren't viable in my situation.
推荐答案
如果要在jOOQ中重用命名参数,最好在外部创建AST元素查询的内容,例如:
If you want to reuse a named parameter in jOOQ, ideally, you create the AST element outside of the query, as such:
// Assuming a static import
import static org.jooq.impl.DSL.*;
Param<Integer> myId = param("myId", Integer.class);
然后您可以在查询中多次使用它:
You can then use it multiple times in your query:
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))
)
);
这篇关于jOOQ插入到..中,对于Postgres不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!