我正在尝试使用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();
目前它正在插入记录正常,但是当基于唯一约束找到重复记录时,它应该更新记录
答案 0 :(得分:1)
我已经通过使用公共接口UpdatableRecord解决了这个问题,首先我使用了fetchOne()查询来获取基于唯一约束的记录,该约束将给出UpdatableRecord,然后使用更新的值设置值。然后添加到userRecordlist,这将进一步传递到batchStore
答案 1 :(得分:0)
我必须和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();