简体   繁体   English

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

[英]Using the JDBC getGeneratedKeys function in multithreaded environment

I have an web application that uses the AUTO INCREMENT value of one table to insert into other tables.我有一个 Web 应用程序,它使用一个表的AUTO INCREMENT值插入到其他表中。 I need to ensure that the value read for the Auto Increment column is correct in the presence of potential concurrent INSERT s into that table.我需要确保在存在潜在并发INSERT到该表的情况下为 Auto Increment 列读取的值是正确的。 Since each thread will have its own connection (from the container pool) do I still have to put the code within a transaction?由于每个线程都有自己的连接(来自容器池),我还需要将代码放在事务中吗?

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();
}

The value of autoincrement of the column is managed on database level.列的自动增量值在数据库级别进行管理。 Therefore you can fetch the value to getGeneratedKeys() without worry in multithreaded environment.因此,您可以在多线程环境中轻松获取getGeneratedKeys()的值。

The transaction is started as soon as you call the update SQL statement.只要您调用更新 SQL 语句,事务就会启动。 It happens on database level.它发生在数据库级别。 It stays open until you commit it manually or if autocommit is enabled.它保持打开状态,直到您手动提交或启用自动提交。

If you need to get more info about transactions, see Java Tutorial .如果您需要获取有关事务的更多信息,请参阅Java 教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM