java getting SQL next sequence number of the record before insertion java getting SQL next sequence number of the record before insertion sql sql

java getting SQL next sequence number of the record before insertion


By using that approach, you should query first for the new identity value (I see you're using sequences),. This can be done by issuing a select.

// This example is for OracleString sqlIdentifier = "select TESTING_SEQ.NEXTVAL from dual";PreparedStatement pst = conn.prepareStatement(sqlIdentifier);synchronized( this ) {   ResultSet rs = pst.executeQuery();   if(rs.next())     long myId = rs.getLong(1);

After that, pass it to the preparedStatement as an argument.

...String sqlInsert = "INSERT INTO TESTING VALUES(?, ?, ?)";PreparedStatement pst = conn.prepareStaetment(sqlInsert);pst.setLong(1, myId);...

From that point, you will always have your sequence number.

These are not functional examples (no catch or finally, etc), but will give you an idea of how to do it ;)


In spring and Oracle database, this should work.

public Long getSequence() {  org.springframework.jdbc.core.JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource);  Long seq;  String sql = "select SEQ_XY.NEXTVAL from dual";  seq = jdbcTemplateObject.queryForObject(sql, new Object[] {}, Long.class);  return seq;}


In Oracle you can use

long myId = rs.getLong("NEXTVAL");

This will fail for HSQL.You can modify the sql statement, by adding "as NEXTVAL".

String sqlIdentifier = "select TESTING_SEQ.NEXTVAL as NEXTVAL from dual";