I am trying to perform an UPSERT in PostgreSQL using the jOOQ library.
For doing this I am currently trying to implement the following SQL statement in jOOQ: https://st
Seems a bit of a complicated way of achieving the objective. Why not use a simple stored fucntion? how to create an upsert function is described in the postgresql manual then just call it from your java code.
jOOQ 3.7+ supports PostgreSQL 9.5's ON CONFLICT
clause:
The full PostgreSQL vendor-specific syntax is not yet supported, but you can use the MySQL or H2 syntax, which can both be emulated using PostgreSQL's ON CONFLICT
:
INSERT .. ON DUPLICATE KEY UPDATE
:DSL.using(configuration)
.insertInto(TABLE)
.columns(ID, A, B)
.values(1, "a", "b")
.onDuplicateKeyUpdate()
.set(A, "a")
.set(B, "b")
.execute();
MERGE INTO ..
DSL.using(configuration)
.mergeInto(TABLE, A, B, C)
.values(1, "a", "b")
.execute();
Here is an upsert utility method derived from Lucas' solution above for UpdatableRecord objects:
public static int upsert(final DSLContext dslContext, final UpdatableRecord record) {
return dslContext.insertInto(record.getTable())
.set(record)
.onDuplicateKeyUpdate()
.set(record)
.execute();
}
Inspired by @ud3sh comment with JOOQ 3.11, Kotlin, and the PostgreSQL DSL
This is an extension function to call upsert
directly on the UpdatableRecord
object
import org.jooq.UpdatableRecord
internal fun UpdatableRecord<*>.upsert(): Int {
if(this.configuration() == null) {
throw NullPointerException("Attach configuration to record before calling upsert")
}
return this.configuration().dsl().insertInto(this.getTable()).set(this).onConflict().doUpdate().set(this).execute()
}