如何在使用JOOQ插入可更新记录时忽略重复键错误

huangapple 未分类评论43阅读模式
英文:

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会被从数据库中的值更新,例如,如果表具有自增列idmyRecord.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(&quot;value&quot;);
  myRecord = dsl
     .insertInto(MY_TABLE)
     .set(myRecord)
     .onDuplicateKeyUpdate()
     .set(myRecord)
     .returning()
     .fetch();
  txn.commit();
}

huangapple
  • 本文由 发表于 2020年4月4日 08:33:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/61022357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定