英文:
How to ignore duplicate key errors when inserting an updatable record with JOOQ
问题
我目前正在使用JOOQ,并遵循以下插入模式使用可更新记录:
MyRecord myRecord = new MyRecord();
try (var txn = tm.beginWriteTransaction()) {
myRecord.setA("value");
myRecord.insert();
txn.commit();
}
在txn.commit()
之后,我期望myRecord
会被从数据库中的值更新,例如,如果表具有自增列id
,myRecord.getId()
将返回其值。
如果列a
具有唯一约束,当违反约束时,txn.commit()
会抛出DataAccessException
。
我的问题是,是否有可能告诉JOOQ不要抛出异常,而仍然使用现有值更新记录呢?
英文:
I'm currently using JOOQ with updatable records following this pattern for inserts:
MyRecord myRecord = new MyRecord();
try (var txn = tm.beginWriteTransaction()) {
myRecord.setA("value");
myRecord.insert();
txn.commit();
}
After txn.commit()
, I expect myRecord
to be updated with values from the database, e.g. if the table has an auto-incremented column id
, myRecord.getId()
will return its value.
If the column a
has a unique constraint, txn.commit()
will throw a DataAccessException
when it is violated.
My question is it possible to tell JOOQ to not throw an exception but still update the record with the existing values?
答案1
得分: 0
有一个未处理的功能请求,希望为UpdatableRecord
添加UPSERT
功能:#1234。
与此同时,您可以将您的记录嵌入到普通的SQL查询中:
MyRecord myRecord = new MyRecord();
try (var txn = tm.beginWriteTransaction()) {
myRecord.setA("value");
myRecord = dsl
.insertInto(MY_TABLE)
.set(myRecord)
.onDuplicateKeyUpdate()
.set(myRecord)
.returning()
.fetch();
txn.commit();
}
英文:
There's a pending feature request to add UPSERT
capabilities to UpdatableRecord
: #1234.
In the meantime, you can embed your record in an ordinary SQL query:
<!-- language: lang-java -->
MyRecord myRecord = new MyRecord();
try (var txn = tm.beginWriteTransaction()) {
myRecord.setA("value");
myRecord = dsl
.insertInto(MY_TABLE)
.set(myRecord)
.onDuplicateKeyUpdate()
.set(myRecord)
.returning()
.fetch();
txn.commit();
}
专注分享java语言的经验与见解,让所有开发者获益!
评论