We have multiple tables and all are related with first table's primary key (example: id). Id is configured as a sequence and while inserting data into to first table we are using sequence.nextval
in the insert query. Now while inserting data to other tables, how to get current sequence value or current Id.
我们有多个表,并且都与第一个表的主键相关(例如:id)。 Id配置为序列,在将数据插入第一个表时,我们在insert查询中使用sequence.nextval。现在,在将数据插入其他表时,如何获取当前序列值或当前Id。
We have tried below options:
我们尝试过以下选项:
-
sequence.currval
, directly in the insert statement 2.select sequence.currval from dual
sequence.currval,直接在insert语句中2.select sequence.currval from dual
Above two options throwing error while using getJdbcTemplate().update()
.
使用getJdbcTemplate()。update()时,上面两个选项抛出错误。
Could anyone please suggest how to get current sequence value to pass to other tables after inserting data into first table??
任何人都可以建议如何在将数据插入第一个表后将当前序列值传递给其他表?
1 个解决方案
#1
If you want to insert the same id (which comes from a sequence) to different tables, simple get it form the first insert and use it in the other inserts.
如果要将相同的id(来自序列)插入到不同的表中,只需将其从第一个插入中获取并在其他插入中使用它。
PrepearedStatement stmt1 = conn.prepareStatement("INSERT INTO TABLE1 (id) VALUES(yoursequence.nextval)", Statemet.RETURN_GENERATED_KEYS);
stmt1.executeUpdate();
ResultSet rs = stmt1.getGeneratedKeys();
rs.next();
long id = rs.getLong(1);
PrepearedStatement stmt2 = conn.prepareStatement("INSERT INTO TABLE2 (id) VALUES(?)");
stmt2.setLong(1,id);
stmt2.executeUpdate();
#1
If you want to insert the same id (which comes from a sequence) to different tables, simple get it form the first insert and use it in the other inserts.
如果要将相同的id(来自序列)插入到不同的表中,只需将其从第一个插入中获取并在其他插入中使用它。
PrepearedStatement stmt1 = conn.prepareStatement("INSERT INTO TABLE1 (id) VALUES(yoursequence.nextval)", Statemet.RETURN_GENERATED_KEYS);
stmt1.executeUpdate();
ResultSet rs = stmt1.getGeneratedKeys();
rs.next();
long id = rs.getLong(1);
PrepearedStatement stmt2 = conn.prepareStatement("INSERT INTO TABLE2 (id) VALUES(?)");
stmt2.setLong(1,id);
stmt2.executeUpdate();