我决定尝试在我的dao类中使用PostgreSQL UPSERT。当我使用DB(7是现有记录)测试此查询时,它会按预期更新游戏。
INSERT INTO games (id, title, description, publisher)
VALUES (7, 'SomeGame444', 'someDesc', 'SomePublisher')
ON CONFLICT (id) DO UPDATE
SET title = EXCLUDED.title, description = EXCLUDED.description, publisher =
EXCLUDED.publisher;
如何使用DB中的PostgreSQL序列创建新ID。所以在我的Java应用程序中,我首先省略了SQL查询中的ID,并且只执行了插入。
阅读此question后,我添加了一个default
关键字来表示序列值。
还有一个问题 - 当我尝试更新现有记录时,它会创建一个带有新ID的新记录。我希望它能用现有ID更新游戏,并在游戏没有ID时创建一个新游戏。
PreparedStatement或SQL查询有问题吗?
public void createOrUpDateGame(Game newGame) {
String sql = "INSERT INTO games (id, title, description, publisher) " +
"VALUES (default, ?, ?, ?)\n" +
"ON CONFLICT (id) DO UPDATE SET " +
"title = EXCLUDED.title, description = EXCLUDED.description, publisher = EXCLUDED.publisher;";
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, newGame.getTitle());
preparedStatement.setString(2, newGame.getDescription());
preparedStatement.setString(3, newGame.getPublisher());
preparedStatement.execute();
} catch (SQLException e) {
System.out.println("Game insert exception");
} finally {
JdbcUtils.closeQuietly(preparedStatement);
JdbcUtils.closeQuietly(connection);
}
}