在spring中使用jdbctemplateFire Sequence.nextval查询

问题描述 投票:0回答:3

数据库:

Oracle

我有一个表,其中有 10 列,我希望在插入行时序列下一个值,并使用插入的序列号。

现在我搜索了一下,发现spring的KeyHolder很有用,但仅限于少于8个字段,所以我不能使用它。

我如何触发

"select MySequence.nextval from dual"
查询并使用
jdbctemplate(NamedParameterJDBCTemplate)
获取序列?

还有其他方法可以实现获取插入的序列值吗?

java database spring oracle jdbctemplate
3个回答
10
投票

使用

jdbctemplate
,您可以将序列生成器作为值提及,例如

jdbcTemplate.update("INSERT INTO TABLE (id, data) VALUES (MySequence.nextval, ?)", new Object[] { data });

关于序列生成的注释:对于 Oracle 12c 之前的版本,您应该有一个触发器来为您增加序列。从 12c 开始您可以使用自动增量功能。


7
投票

您可以通过使用 JdbcTemplate 来实现这一点,如下所示:

final SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(NEXT_VALUE_QUERY);
  sqlRowSet.next();// mandatory to move the cursor 
  sqlRowSet.getLong(1);// the value of the nextval

0
投票

以防万一有人偶然发现这个老问题。

使用 GeneratedKeyHolderPreparedStatementCreator 列数没有限制,您可以直接获取 ID(不需要 MySequence.nextval)。

JdbcTemplate jdbcTemplate;

String sql = "INSERT INTO TABLE (ID, DATA) VALUES (MySequence.nextval, ?)";

KeyHolder keyHolder = new GeneratedKeyHolder();

PreparedStatementCreator preparedStatementCreator = connection -> {
    PreparedStatement ps = connection.prepareStatement(sql, new Object[]{"EMPLOYEE_ID"});
    ps.setString(1, name);
    ps.setString(2, department);
    return ps;
};

jdbcTemplate.update(preparedStatementCreator, keyHolder);

long id = keyHolder.getKey().longValue();
© www.soinside.com 2019 - 2024. All rights reserved.