From a05da202afc1994e1f175b628327dd3502b440d6 Mon Sep 17 00:00:00 2001 From: Michael Bayne Date: Thu, 20 Feb 2025 10:32:16 -0800 Subject: [PATCH] Add mechanism to get auto-generated key to JORA. This assumes that the JDBC driver supports getGeneratedKeys(), which is a safe bet in these rarified modern times. --- .../java/com/samskivert/jdbc/jora/Table.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/main/java/com/samskivert/jdbc/jora/Table.java b/src/main/java/com/samskivert/jdbc/jora/Table.java index cdd0cab4..59dbe012 100644 --- a/src/main/java/com/samskivert/jdbc/jora/Table.java +++ b/src/main/java/com/samskivert/jdbc/jora/Table.java @@ -218,6 +218,40 @@ public class Table insertStmt.close(); } + /** + * Insert new record in the table. Values of inserted record fields are taken from specified + * object. Returns the auto-generated key assigned by the database to the new row. Note: this + * only works for tables with a single primary key and relies on the caller to indicate the type + * of the key (`Integer`, `String`, etc) via the generic method parameter. + * + * @param obj object specifying values of inserted record fields + * @return the auto-generated key created by the database. + */ + public synchronized K insertGetKey (Connection conn, T obj) throws SQLException + { + if (primaryKeys.length > 1) throw new UnsupportedOperationException( + "Table must have exactly one primary-key column. This table has " + primaryKeys.length); + StringBuilder sql = new StringBuilder( + "insert into " + name + " (" + listOfFields + ") values (?"); + for (int i = 1; i < nColumns; i++) { + sql.append(",?"); + } + sql.append(")"); + PreparedStatement insertStmt = conn.prepareStatement( + sql.toString(), Statement.RETURN_GENERATED_KEYS); + bindUpdateVariables(insertStmt, obj, null); + insertStmt.executeUpdate(); + ResultSet rs = insertStmt.getGeneratedKeys(); + Object rawKey = null; + if (rs.next()) { + rawKey = rs.getObject(primaryKeys[0]); + } + @SuppressWarnings("unchecked") + K key = (K)rawKey; + insertStmt.close(); + return key; + } + /** * Insert several new records in the table. Values of inserted records * fields are taken from objects of specified array.