我正在尝试使用jOOQ库在PostgreSQL中执行UPSERT。
为此,我目前正在尝试在jOOQ中实现以下SQL语句: https://stackoverflow.com/a/6527838
到目前为止,我的代码看起来像这样:
public class UpsertExecutor {
private static final Logger logger = LoggerFactory.getLogger(UpsertExecutor.class);
private final JOOQContextProvider jooqProvider;
@Inject
public UpsertExecutor(JOOQContextProvider jooqProvider) {
Preconditions.checkNotNull(jooqProvider);
this.jooqProvider = jooqProvider;
}
@Transactional
public <T extends Record> void executeUpsert(Table<T> table, Condition condition, Map<? extends Field<?>, ?> recordValues) {
/*
* All of this is for trying to do an UPSERT on PostgreSQL. See:
* https://stackoverflow.com/a/6527838
*/
SelectConditionStep<Record1<Integer>> notExistsSelect = jooqProvider.getDSLContext().selectOne().from(table).where(condition);
SelectConditionStep<Record> insertIntoSelect = jooqProvider.getDSLContext().select(recordValues).whereNotExists(notExistsSelect);
try {
int[] result = jooqProvider.getDSLContext().batch(
jooqProvider.getDSLContext().update(table).set(recordValues).where(condition),
jooqProvider.getDSLContext().insertInto(table).select(insertIntoSelect)
).execute();
long rowsAffectedTotal = 0;
for (int rowsAffected : result) {
rowsAffectedTotal += rowsAffected;
}
if (rowsAffectedTotal != 1) {
throw new RuntimeException("Upsert must only affect 1 row. Affected: " + rowsAffectedTotal + ". Table: " + table + ". Condition: " + condition);
}
} catch (DataAccessException e) {
if (e.getCause() instanceof BatchUpdateException) {
BatchUpdateException cause = (BatchUpdateException)e.getCause();
logger.error("Batch update error in upsert.", cause.getNextException());
}
throw e;
}
}
}
但是这段代码不能编译,因为select()不支持值映射:
SelectConditionStep<Record> insertIntoSelect = jooqProvider.getDSLContext().select(recordValues).whereNotExists(notExistsSelect);
如何为select()提供一组预定义的值,如下所示:SELECT 3, 'C', 'Z'
?
我设法让代码正常运行。这是完整的课程:
public class UpsertExecutor {
private static final Logger logger = LoggerFactory.getLogger(UpsertExecutor.class);
private final JOOQContextProvider jooqProvider;
@Inject
public UpsertExecutor(JOOQContextProvider jooqProvider) {
Preconditions.checkNotNull(jooqProvider);
this.jooqProvider = jooqProvider;
}
@Transactional
public <T extends Record> void executeUpsert(Table<T> table, Condition condition, List<FieldValue<Field<?>, ?>> recordValues) {
/*
* All of this is for trying to do an UPSERT on PostgreSQL. See:
* https://stackoverflow.com/a/6527838
*/
Map<Field<?>, Object> recordValuesMap = new HashMap<Field<?>, Object>();
for (FieldValue<Field<?>, ?> entry : recordValues) {
recordValuesMap.put(entry.getFieldName(), entry.getFieldValue());
}
List<Param<?>> params = new LinkedList<Param<?>>();
for (FieldValue<Field<?>, ?> entry : recordValues) {
params.add(val(entry.getFieldValue()));
}
List<Field<?>> fields = new LinkedList<Field<?>>();
for (FieldValue<Field<?>, ?> entry : recordValues) {
fields.add(entry.getFieldName());
}
SelectConditionStep<Record1<Integer>> notExistsSelect = jooqProvider.getDSLContext().selectOne().from(table).where(condition);
SelectConditionStep<Record> insertIntoSelect = jooqProvider.getDSLContext().select(params).whereNotExists(notExistsSelect);
try {
int[] result = jooqProvider.getDSLContext().batch(
jooqProvider.getDSLContext().update(table).set(recordValuesMap).where(condition),
jooqProvider.getDSLContext().insertInto(table, fields).select(insertIntoSelect)
).execute();
long rowsAffectedTotal = 0;
for (int rowsAffected : result) {
rowsAffectedTotal += rowsAffected;
}
if (rowsAffectedTotal != 1) {
throw new RuntimeException("Upsert must only affect 1 row. Affected: " + rowsAffectedTotal + ". Table: " + table + ". Condition: " + condition);
}
} catch (DataAccessException e) {
if (e.getCause() instanceof BatchUpdateException) {
BatchUpdateException cause = (BatchUpdateException)e.getCause();
logger.error("Batch update error in upsert.", cause.getNextException());
}
throw e;
}
}
}
但List<FieldValue<Field<?>, ?>> recordValues
参数确实不太干净。关于如何做到这一点的任何更好的想法?
答案 0 :(得分:16)
jOOQ 3.7+支持PostgreSQL 9.5的ON CONFLICT
子句:
尚不支持完整的PostgreSQL供应商特定语法,但您可以使用MySQL或H2语法,这两种语法都可以使用PostgreSQL的ON CONFLICT
进行模拟:
INSERT .. ON DUPLICATE KEY UPDATE
:DSL.using(configuration)
.insertInto(TABLE)
.columns(ID, A, B)
.values(1, "a", "b")
.onDuplicateKeyUpdate()
.set(A, "a")
.set(B, "b")
.execute();
MERGE INTO ..
DSL.using(configuration)
.mergeInto(TABLE, A, B, C)
.values(1, "a", "b")
.execute();
答案 1 :(得分:9)
这是一个upsert实用程序方法,它源自上面针对UpdatableRecord对象的Lucas解决方案:
public static int upsert(final DSLContext dslContext, final UpdatableRecord record) {
return dslContext.insertInto(record.getTable())
.set(record)
.onDuplicateKeyUpdate()
.set(record)
.execute();
}
答案 2 :(得分:3)
似乎有点复杂的方法来实现目标。为什么不使用简单的存储功能?如何创建一个upsert函数在postgresql manual中描述,然后从你的java代码中调用它。
答案 3 :(得分:1)
受到@ ud3sh的JOOQ 3.11,Kotlin和PostgreSQL DSL启发,
这是一个扩展函数,可以直接在upsert
对象上调用UpdatableRecord
import org.jooq.UpdatableRecord
internal fun UpdatableRecord<*>.upsert(): Int {
if(this.configuration() == null) {
throw NullPointerException("Attach configuration to record before calling upsert")
}
return this.configuration().dsl().insertInto(this.getTable()).set(this).onConflict().doUpdate().set(this).execute()
}