Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return id in ON DUPLICATE KEY in JOOQ

What I actually want is to write following query in JOOQ:

stmt = connection.prepareStatement(
    "INSERT INTO `tbl` (`name`, `service_id`, `device_id`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `id` = LAST_INSERT_ID(`id`)", 
    Statement.RETURN_GENERATED_KEYS
);

I'm not able to find a way to do this in JOOQ. Is it possible?

like image 325
Majid Azimi Avatar asked Oct 19 '14 06:10

Majid Azimi


People also ask

How do you use duplicate keys?

ON DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas. The use of VALUES() to refer to the new row and columns is deprecated beginning with MySQL 8.0.

How do I ignore a duplicate key?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

What is duplicate key value in SQL?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.


2 Answers

Currently (as of jOOQ 3.4-3.6), that's not possible due to a flaw in jOOQ's INSERT API:

  • https://github.com/jOOQ/jOOQ/issues/2123
like image 80
Lukas Eder Avatar answered Nov 04 '22 05:11

Lukas Eder


This might help you. For time being I am using this:

Field<Integer> LAST_INSERT_ID = DSL.function("LAST_INSERT_ID", Integer.class, PACKAGE.ID);

dsl.insertInto(PACKAGE)
   .set(dsl.newRecord(PACKAGE, packagePojo))
   .onDuplicateKeyUpdate()
   .set(PACKAGE.ID, LAST_INSERT_ID)
   .set(PACKAGE.PTR_JOB, packagePojo.getPtrJob())
   .set(PACKAGE.PACK_NUMBER, packagePojo.getPackNumber())
   .set(PACKAGE.RACK, packagePojo.getRack()
like image 1
Tomas Avatar answered Nov 04 '22 06:11

Tomas