Oracle Java JDBC: Get Primary Key of Inserted record

oracle-logoHere is a small write-up which should help those who still write plain Java JDBC code. I know we have some wonderful persistence frameworks like Hibernate that make ones life comfortable but the reality is we still have to deal with plain old JDBC apis. If you are poor chap like me, below code should make your life easy.

Problem statement:

I just inserted a record in Oracle database using Java JDBC. The primary key column was auto populated by a sequence value. How should I get the last inserted records auto generated primary key?

Solution:

The solution should be getGeneratedKeys(). This method was added in JDBC 3.0 and it should be used to get last auto generated key value.

See code snippet below:

PreparedStatement prepareStatement = connection.prepareStatement("insert...",
		new String[] { "your_primary_key_column_name" });

prepareStatement.executeUpdate();

ResultSet generatedKeys = prepareStatement.getGeneratedKeys();
if (null != generatedKeys && generatedKeys.next()) {
     Long primaryKey = generatedKeys.getLong(1);
}

The above code should give us auto generated primary key value. The one thing to note here is method prepareStatement(). We passed two arguments first the insert query string and second an array of column name. The column name should be the primary key column name of table where you inserting the record.

Check below source code to see complete solution.

Full solution

We have a database table called STUDENTS. We also have an oracle sequence called STUDENT_SEQ that we uses to generate primary key for STUDENTS table.

CREATE TABLE STUDENTS
(
   STUDENT_ID   NUMBER NOT NULL PRIMARY KEY,
   NAME         VARCHAR2 (50 BYTE),
   EMAIL        VARCHAR2 (50 BYTE),
   BIRTH_DATE   DATE
);


CREATE SEQUENCE STUDENT_SEQ
   START WITH 0
   MAXVALUE 9999999999999999999999999999
   MINVALUE 0;

In Java, we use plain JDBC calls to insert a record in STUDENTS table. We uses sequence STUDENT_SEQ to generate primary key. Once the record is inserted, we want the last inserted primary value.

String QUERY = "INSERT INTO students "+
               "  VALUES (student_seq.NEXTVAL,"+
               "         'Harry', 'harry@hogwarts.edu', '31-July-1980')";

// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");

// get database connection from connection string
Connection connection = DriverManager.getConnection(
		"jdbc:oracle:thin:@localhost:1521:sample", "scott", "tiger");

// prepare statement to execute insert query
// note the 2nd argument passed to prepareStatement() method
// pass name of primary key column, in this case student_id is
// generated from sequence
PreparedStatement ps = connection.prepareStatement(QUERY,
		new String[] { "student_id" });

// local variable to hold auto generated student id
Long studentId = null;

// execute the insert statement, if success get the primary key value
if (ps.executeUpdate() > 0) {

	// getGeneratedKeys() returns result set of keys that were auto
	// generated
	// in our case student_id column
	ResultSet generatedKeys = ps.getGeneratedKeys();

	// if resultset has data, get the primary key value
	// of last inserted record
	if (null != generatedKeys && generatedKeys.next()) {

		// voila! we got student id which was generated from sequence
		studentId = generatedKeys.getLong(1);
	}

}

The above code is filled with comments and is pretty self explanatory. Finally we have last inserted value in studentId variable.

The getGeneratedKeys() method is key here. It gives us the result set of all auto generated key values. In our case as we have only one auto generated value (for student_id column) we get only single record in this result set.



Tags: ,

7 Comments

  • Bruce 8 October, 2013, 2:55

    And if your primary key is not generated by the SQL “student_id.nextval” but a trigger from the insert statement?

    • Jawwad 9 October, 2013, 11:14

      It also works in that case. I have a ‘Before Insert’ trigger which gets the latest primary key from Sequence and

      ps.getGeneratedKeys()

      works in that case.

  • sivu 9 October, 2013, 2:19

    Thanks a lot for the valuable post.
    For every row inserted in a table i need the primary key value of that record to insert a record in other table. So is it possible to ps.getGeneratedKeys() after ps.executeBatch()
    Thanks a lot.

  • Sarkhan nagiyev 14 February, 2014, 16:58

    Thanks a lot !

  • Zoltan Etedi 21 February, 2014, 18:59

    Thanks! :)

  • Csanád 2 September, 2014, 12:56

    Thanks I’ve searching for this for days

  • Paras 21 November, 2014, 3:56

    Can we use some prefix with sequence NEXTVAL with prepared statement without executing separate query for sequence for example:

    String requestID = “EMP||PENDING_TABLE_SEQ.nextval”;
    preparedStatement = connection.prepareStatement(“INSERT INTO IMPL_PENDING_TABLE (MANUAL_REQUEST_ID,CREATION_USER_ID,CREATION_USER_BU_ID,CREATION_SOURCE,GAIA_ID,CUSTOMER_ID,EMAIL_ADDRESS,UI_DESCRIPTION,STATUS) VALUES (“+requestID +”,?,?,?,?,?,?,?,?)”);

    The above code need single quote around primary key but if I use single quote then it does not identify seq.nextval.

    Do we have any way ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *