UPSERT in PostgreSQL using jOOQ

后端 未结 4 1800
死守一世寂寞
死守一世寂寞 2021-02-03 19:31

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

相关标签:
4条回答
  • 2021-02-03 19:42

    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.

    0 讨论(0)
  • 2021-02-03 19:46

    jOOQ 3.7+ supports PostgreSQL 9.5's ON CONFLICT clause:

    • https://github.com/jOOQ/jOOQ/issues/4299
    • http://www.postgresql.org/docs/9.5/static/sql-insert.html

    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:

    MySQL 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();
    

    H2 MERGE INTO ..

    DSL.using(configuration)
       .mergeInto(TABLE, A, B, C)
       .values(1, "a", "b")
       .execute();
    
    0 讨论(0)
  • 2021-02-03 20:01

    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();
    }
    
    0 讨论(0)
  • 2021-02-03 20:06

    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()
    }
    
    0 讨论(0)
提交回复
热议问题