2

如何在批量更新中使用乐观锁定?我正在使用SimpleJdbcTemplate单行,我可以构建更新 sql,它增加版本列值并在 WHERE 子句中包含版本。

不幸的是int[] updated = simpleJdbcTemplate.batchUpdate,使用 oracle 驱动程序时结果不包含行数。所有元素都是 -2 表示未知的行数。

除了单独执行所有更新之外,还有其他更高效的方法吗?这些批次平均包含 5 个项目(仅),但可能多达 250 个。

4

2 回答 2

2

Just thinking aloud here - if it's a problem with the batch support in the driver, you could try to achieve the same using a single query, making batching less relevant. (As you know, batching is about avoiding latency with multiple queries, but latency is still present even when batching a single query.)

Here's how you might achieve the optimistic update with a single query

  • Build a temporary table that contains the conditions necessary for a row update, and rewrite your update query to be a join on this table. (e.g. outer join the current timestamp in the live data with the timestamp in your temporary table.) If the timestamp on the live data has not been updated then the row will be selected from your temporary table.

Since you can use the temporary table as a select query, you can find which rows would be updated, and then submit this as an update query. (All within a transaction, of course.)

To illustrate:

TempUpdateTable
---------------
id,        // id of the row to be updated
timestamp, // timestamp data originally fetched
data1      // data to be updated
data2
dataN

This gives the ids of all data to be updated, which you can store for later reference

SELECT d.id FROM TempUpdateTable t JOIN YourData d 
    ON t.id=d.id WHERE t.timestamp=d.timestamp

The same query can then be used in an update statement

UPDATE YourData
SET data=t.data1
SET data=t.data2  //etc...
FROM TempUpdateTable t WHERE t.id IN
  (SELECT d.in FROM TempUpdateTable t JOIN YourData d 
    ON t.id=d.id WHERE d.timestamp=d.timestamp)
于 2010-05-29T05:41:28.120 回答
1

当我为 Hibernate 工作时,我们注意到旧的 Oracle JDBC 驱动程序版本没有正确报告更新计数,这就是为什么 Hibernate 曾经使用乐观锁定禁用实体的批量更新。

但是,从 Hibernate 5 开始,这不再是默认策略,因为 JDBC 驱动程序可以更好地处理批量更新计数。

因此,在您的情况下,您需要将 Oracle JDBC 驱动程序更新到至少 12c。请注意,Oracle JDBC 驱动程序向后和向前兼容,因此您甚至可以在数据库服务器端与 Oracle 11g 一起使用它。

自 2019 年 9 月起,您甚至可以从 Maven Central 获取 Oracle JDBC 驱动程序:

<dependency>
    <groupId>com.oracle.ojdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>19.3.0.0</version>
</dependency>

我正在使用带有 Oracle 18 XE 的驱动程序版本 19,即使将批量更新与乐观锁定混合使用,它也能发挥出色的作用。

于 2019-11-26T11:14:45.680 回答