【问题标题】:Update record on unique constraint on batch store jooq更新批量存储 jooq 上唯一约束的记录
【发布时间】:2018-02-23 00:04:52
【问题描述】:

我正在尝试使用 jooq 使用 batchStore 插入记录。我需要知道我们如何更新唯一约束的记录,目前它正在抛出 记录已存在的异常

SQL Error [23505]: ERROR: duplicate key value violates unique constraint

下面是代码

DSLContext create = getDSLContext();
List<UserRecord> userRecordList = new ArrayList<>();
for (Users user : model.getUsers()) {
    User record = create.newRecord(user);
    userRecordList.add(record);
}
create.batchStore(userRecordList).execute();

目前插入记录正常,但是当基于唯一约束发现重复记录时,它应该更新记录

【问题讨论】:

  • 确实,batchStore() 命令不执行 SQL MERGE 语句语义,而是在每条记录上调用 UpdatableRecord.store() 的快捷方式,批量运行 store() 命令。有一个改进文档的功能请求:github.com/jOOQ/jOOQ/issues/6584

标签: java postgresql jooq


【解决方案1】:

我已经通过使用通用接口 UpdatableRecord 解决了这个问题,首先我使用 fetchOne() 查询根据唯一约束获取记录,该约束将提供 UpdatableRecord,然后使用更新的值设置这些值然后将其添加到 userRecordlist 中,该 userRecordlist 将进一步传递到 batchStore

【讨论】:

    【解决方案2】:

    我必须和 JN_newbie 一样。为了完整起见,这是我的解决方案的样子。

    // OpeningtimeRecord is the JOOG generated record for the Openingtime table.
    List<OpeningtimeRecord> openingRecords = new ArrayList<>();
    
    // Openingtime is the POJO generated from the database schema for the table.
    for (Openingtime opening : openings)
    {
        // Check to see if this record already exists in the database
        OpeningtimeRecord record = dbContext.fetchOne(*TABLE*, *TABLE.ID*.eq(opening.getId()));
    
        // If it doesn't exist then we need to create a new record
        if (null == record)
        {
            record = dbContext.newRecord(*TABLE*, opening);
        }
        else
        {
            // Update the record with any new data from the POJO.
            record.from(opening);
        }
    
        openingRecords.add(record);
    }
    
    int[] results = this.dbContext.batchStore(openingRecords).execute();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2019-12-24
      • 2017-01-10
      • 2012-09-17
      • 2017-12-29
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多