创建表:
CREATE TABLE tests (id SERIAL PRIMARY KEY, "name" VARCHAR);
UPSERT:
INSERT INTO tests (id, "name")
VALUES (?, ?)
ON CONFLICT (id) DO UPDATE
SET "name" = EXCLUDED."name";
问题在于它永远不会执行UPDATE部分,因为SERIAL类型可以解决所有冲突-它只是将现有记录作为具有新ID(nextval)的新记录插入,而不是对其进行更新。
我正在尝试实现“保存所有记录”功能。它应该更新现有记录,如果不存在则插入新记录。
我想象的算法:
connection.setAutoCommit(false);
for (Test test : tests)
{
statement = connection.prepareStatement("INSERT INTO tests (id, \"name\") VALUES (?, ?) ON CONFLICT (id) DO UPDATE SET \"name\" = EXCLUDED.\"name\";");
statement.setInt(1, test.getId());
statement.setString(2, test.getName());
statement.execute();
}
connection.commit();