在多线程环境中使用JDBC getGeneratedKeys函数

问题描述 投票:0回答:1

我有一个Web应用程序,它使用一个表的AUTO INCREMENT值插入到其他表中。我需要确保在存在可能的并发INSERT到该表时,为自动增量列读取的值是正确的。由于每个线程都有自己的连接(来自容器池),我还需要将代码放在事务中吗?

PreparedStatement ps = null;
ResultSet rs = null;
String sql = "INSERT INTO KYC_RECORD ....";
int autoIncKeyFromApi = -1;

Connection connection = ....

try {

    connection.setAutoCommit(false);

    ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

    ps.setString( ... );

    ps.executeUpdate();

    rs = ps.getGeneratedKeys();

    if (rs.next()) {
        autoIncKeyFromApi = rs.getInt(1);
    } else {

        // throw an exception from here
    }

    connection.commit();
}
java mysql multithreading jdbc auto-increment
1个回答
0
投票

列的自动增量值在db级别上进行管理。因此,您可以在多线程环境中获取值以无需担心获取键。

一旦调用更新SQL语句,就会启动事务。它发生在db级别。在您手动提交或启用自动提交之前,它将保持打开状态。

© www.soinside.com 2019 - 2024. All rights reserved.