4

只是一个关于使用 JDBC 在 postgres 数据库中锁定表的快速问题。我有一个要为其添加新记录的表,但是,要为主键执行此操作,我使用了一个递增的整数值。

我希望能够在 Java 中检索此列的最大值并将其存储为变量,以便在添加新行时用作新的主键。

这给了我一个小问题,因为这将被建模为多用户系统,当 2 个位置请求相同的最大值时会发生什么?当尝试添加相同的主键时,这当然会产生问题。

我意识到我应该在表上使用独占锁来防止在获取密钥和添加新行时读取或写入。但是,我似乎找不到任何方法来处理 JDBC 中的表锁定,只是标准事务。

伪代码如下:

primaryKey = "SELECT MAX(id) FROM table1;";
primary key++;
//id retrieved again from 2nd source

"INSERT INTO table1 (primaryKey, value 1, value 2);"
4

1 回答 1

5

You're absolutely right, if two locations request at around the same time, you'll run into a race condition.

The way to handle this is to create a sequence in postgres and select the nextval as the primary key.

I don't know exactly what direction you're heading and how your handle your data, but you could also set the column as a serial and not even include the column in your insert query. The column will automatically auto increment.

于 2013-03-29T19:07:31.893 回答