我想要实现的一般工作流程是读取MySQL表中的一行,确保它不会被另一个事务更新,并使用新值更新它。
我的代码如下:
iface=...
我的问题是我需要使用SELECT FOR UPDATE查询吗?类似于:https://docs.oracle.com/cd/E17952_01/mysql-5.1-en/innodb-locking-reads.html
当我准备更新语句时,是否需要将并发模式设置为 public PlaceMatchingState updatePlaceMatchingTaskState(
String cId, PlaceMatchingTaskState placeEditTaskState)
throws SQLException, IOException, TException {
String selectQuery = String.format("SELECT * FROM %s.%s WHERE placeId=?;", database, table);
String updateQuery =
String.format("UPDATE %s.%s SET state=? WHERE placeId=?;", database, table);
try (Connection connection = client.getConnection();
PreparedStatement selectStatement = connection.prepareStatement(selectQuery);
PreparedStatement updateStatement = connection.prepareStatement(updateQuery)) {
connection.setAutoCommit(false);
selectStatement.setString(1, cId);
ResultSet queryResult = selectStatement.executeQuery();
List<PlaceMatchingState> result = new ArrayList<>();
while (queryResult.next()) {
byte[] blobInBytes = queryResult.getBytes("state");
PlaceMatchingState placeMatchingState = new PlaceMatchingState();
deserializer.deserialize(placeMatchingState, blobInBytes);
result.add(placeMatchingState);
}
assert result.size() == 1;
PlaceMatchingState updatedEntity =
updatePlaceMatchingTaskState(placeEditTaskState, result.get(0));
updateStatement.setBytes(1, serializer.serialize(updatedEntity));
updateStatement.setString(2, cId);
updateStatement.executeUpdate();
connection.commit();
return updatedEntity;
}
}
?