It’s not uncommon that as part of a complex transaction you need to insert a row into a table with an auto-incrementing primary key and then use the key from the row you just generated as a foreign key in another insert within the same transaction. Java provides a mechanism to return the auto-generated keys from an insert query without the need to execute a second query by means of the function java.sql.Statement.getGeneratedKeys(). Unfortunately the PostgreSQL JDBC connector does not appear to support this feature (at least the version I am using does not). Given the fact that we do not have this functionality available to us when using a PostgreSQL database we need to use a separate query to retreive the value of the key we just generated. It goes without saying that we need to do this two-step process as part of a transaction but it may not go without saying that the correct way to extract the value for the key is by querying the sequence that the key is being generated from and not by querying the table directly. It is true that most of the time the highest value of the incrementing variable will be the value just inserted but that is not a guarantee.

The code to do any database processing in Java always gets long and convoluted. The following is code which has been adapted for a project I’m working on at the moment. I’ve simplified the code to remove distractions from the database logic. Please note that in the code below db is a database connection of type java.sql.Connection. The code shows the generation of a group which requires that a forum be created first and that the ID of that newly created group be included in the query to insert the group into the database.

  1. try{
  2.   // set the connection not to auto commit
  3.   // (i.e. start a transaction)
  4.   db.setAutoCommit(false);
  5.  
  6.   //first create the group forum and get back its ID
  7.   Statement stitf = db.createStatement();
  8.   stitf.execute("INSERT INTO forums (type) VALUES('GROUP')");
  9.   stitf.close();
  10.   Statement stgfid = db.createStatement("SELECT last_value FROM forums_id_seq");
  11.   ResultSet rsgfid = stgfid.executeQuery();
  12.   rsgfid.next();
  13.   int forumId = rsgfid.getInt(1);
  14.   rsgfid.close();
  15.   stgfid.close();
  16.  
  17.   //then create the group
  18.   PreparedStatement psti = db.prepareStatement("INSERT INTO groups (mentor_id, name, wiki_text, anonymous, forum_id) VALUES (?, ?, ?, ?, ?)");
  19.   psti.setString(1, validatedMentorId);
  20.   psti.setString(2, validatedGroupName);
  21.   psti.setString(3, wikiContent.getEve());
  22.   psti.setBoolean(4, anonymous);
  23.   psti.setInt(5, forumId);
  24.   psti.executeUpdate();
  25.   psti.close();
  26.  
  27.   //commit the transaction
  28.   db.commit();
  29. } catch(Exception e) {
  30.   String errorMessage = "An exception occoured while trying to create a group.";
  31.   try {
  32.     db.rollback();
  33.   } catch(Exception ee) {
  34.     errorMessage += " A futher exception occoured when trying to rollback the transaction";
  35.   }
  36.   throw new Exception(errorMessage, e);
  37. }

The important things to notice are the following:

  1. All the activity takes place within a transaction.
  2. If anything goes wrong the transaction is rolled back within the catch block.
  3. The transaction is committed at the end of the try block. If you leave the commit statement out your transaction will never actually appear in the DB!
  4. We retrieved the value of the auto incrementing field (forums(id)) by selecting last_value from the sequence which PostgreSQL automatically generates to go with a field of type SERIAL (i.e. an auto incrementing field). The name of this sequence can be trivially determined from the name of the table and the name of the column. It takes the following form: [tableName]_[columnName]_seq. In the sample code above the table name was forums and the column name was id, hence the sequence being queried being forums_id_seq.