I am using oracle sequence for inserting log id into tableA as follows,
String SQL_PREP_INSERT = "INSERT INTO tableA (LOG_ID,USER_ID,EXEC_TIME) VALUES"
+ " (logid_seq.nextval, ?, ?)";
Then getting the recently inserted value,
String SQL_PREP_SEL = "SELECT max(LOG_ID) FROM tableA ";
stmt = con.prepareStatement(SQL_PREP_SEL);
stmt.execute();
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
logid = rs.getInt(1);
}
And inserting it into tableB,
String SQL_PREP_INSERT_DETAIL = "INSERT INTO tableB (LOG_ID, RESPONSE_CODE, RESPONSE_MSG) VALUES"
+ " (?, ?)";
stmt = con.prepareStatement(SQL_PREP_INSERT_DETAIL);
stmt.setInt(1, logid);
stmt.setString(2, respCode);
stmt.setString(3, respMsg);
stmt.execute();
Is there a way to generate sequence in Java instead of Oracle and insert into both tables at once, instead of selecting from tableA and inserting into tableB?
In general, selecting the
MAX(log_id)is not going to give you the same value thatlogid_seq.nextvalprovided. Assuming that this is a multi-user system, some other user could have inserted another row with a largerlog_idvalue than the row you just inserted before your query is executed.Assuming that both
INSERTstatements are run in the same session, the simplest option is probably to use thelogid_seq.currvalin the secondINSERTstatement.currvalwill return the last value of the sequence that was returned to the current session so it will always return the same value that was generated by thenextvalcall in the first statement.Alternatively, you could use the
RETURNINGclause in your first statement to fetch the sequence value into a local variable and use that in the secondINSERTstatement. But that is probably more work than simply using thecurrval.