0

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.

Community
  • 1
  • 1
malhobayyeb
  • 2,725
  • 11
  • 57
  • 91

2 Answers2

3

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();

if(results.next){
 System.out.println(generatedKeys.getLong(1));
}

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)

Community
  • 1
  • 1
HRgiger
  • 2,750
  • 26
  • 37
1

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.

vlex
  • 128
  • 6