title: Using the JDBC getGeneratedKeys function in multithreaded environment
body: <p>I have an web application that uses the <code>AUTO INCREMENT</code> value of one table to insert into other tables. I need to ensure that the value read for the Auto Increment column is correct in the presence of potential concurrent <code>INSERT</code>s into that table. Since each thread will have its own connection (from the container pool) do I still have to put the code within a transaction?</p>
  <pre class="lang-java prettyprint-override"><code>PreparedStatement ps = null;
  ResultSet rs = null;
  String sql = &quot;INSERT INTO KYC_RECORD ....&quot;;
  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();
  }
  </code></pre>