Take the 2-minute tour ×

Possible Duplicate:
How to get the insert ID in JDBC?

I have the following tables:

customer(cid, ...)

book(cid, rid)

reservation(rid, ...)

I want to add a reservation in its table then I want to add in a relationship in book between customer and reservation.

How can I know rid while it is auto generated, and when I execute the query I did get a ResultSet returned?

The rid is auto generated form Oracle using a sequence and a trigger.

share|improve this question
add comment

marked as duplicate by BalusC, Peter O., mgibsonbr, Alex, Jakob Bowyer Nov 26 '12 at 2:58


2 Answers

up vote 2 down vote accepted

Refer to your question I believe you are using statements. In this case, you can use Statement.RETURN_GENERATED_KEYS. Also please consider this link as below solution can have conficts for Oracle database.

Here is small example:

Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(myQuery, Statement.RETURN_GENERATED_KEYS);
int count = statement.executeUpdate();
if(count <= 0){
 //value not inserted

ResultSet results = statement.getGeneratedKeys();


in case of you are using ORM:

If you are using JPA entitiyManager.merge(entity); (or update) should return persisted instance with ID. Quite similar with hibernate session.merge(entity); (or update)

share|improve this answer
add comment

Dunno how it is with java/jsp, but if it's a relational DB, you'd have to use a set of queries - i.e. get the one id you do know (cid) and then get the rid from the book table. There's no other way I know of.

Hope that helps.

share|improve this answer
add comment
