Jdbc批量更新好key检索策略
我使用 JDBC 的 batchUpdate
功能将大量数据插入到具有自动生成键的表中。因为 JDBC 没有提及任何有关 batchUpdate
和 getAuto generatedKeys
的内容,所以我需要一些独立于数据库的解决方法。
我的想法:
在插入之前以某种方式从数据库中提取下一个分发的序列,然后手动使用密钥。但 JDBC 还没有
getTheNextFutureKeys(howMany)
。那么如何才能做到这一点呢?例如在 Oracle 中拉取密钥是否也保存事务?因此,只有一个事务可以提取相同的一组未来密钥。添加一个带有仅在交易期间有效的虚假 ID 的额外列。
使用所有其他列作为辅助键来获取生成的键。这实际上并不符合 3NF...
是否有更好的想法或者我如何以通用的方式使用想法 1?
I insert alot of data into a table with a autogenerated key using the batchUpdate
functionality of JDBC. Because JDBC doesn't say anything about batchUpdate
and getAutogeneratedKeys
I need some database independant workaround.
My ideas:
Somehow pull the next handed out sequences from the database before inserting and then using the keys manually. But JDBC hasn't got a
getTheNextFutureKeys(howMany)
. So how can this be done? Is pulling keys e.g. in Oracle also transaction save? So only one transaction can ever pull the same set of future keys.Add an extra column with a fake id that is only valid during the transaction.
Use all the other columns as secondary key to fetch the generated key. This isn't really 3NF conform...
Are there better ideas or how can I use idea 1 in a generalized way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
部分答案
是的,从序列中获取值是事务安全的,我的意思是即使您回滚事务,数据库返回的序列值在任何情况下都不会再次返回。
因此,您可以从序列中预取 id-s 并在批量插入中使用它们。
Partial answer
Yes, getting values from a sequence is transaction safe, by which I mean even if you roll back your transaction, a sequence value returned by the DB won't be returned again under any circumstances.
So you can prefetch the id-s from a sequence and use them in the batch insert.
从来没有遇到过这个,所以我深入研究了一下。
首先,有一种方法可以从 JDBC 语句检索生成的 id:
请参阅此 http://download.oracle.com/javase/1.4.2/docs/guide/jdbc/getstart/statement.html#1000569
另外,理论上它可以与 JDBC 结合使用< a href="http://download.oracle.com/javase/1.3/docs/guide/jdbc/spec2/jdbc2.1.frame6.html" rel="nofollow">batchUpdate
虽然,这种组合似乎相当重要,但请参阅此线程。
我建议尝试这个,如果你不成功,就退回到从序列中预取。
Never run into this, so I dived into it a little.
First of all, there is a way to retrieve the generated ids from a JDBC statement:
see this http://download.oracle.com/javase/1.4.2/docs/guide/jdbc/getstart/statement.html#1000569
Also, theoretically it could be combined with the JDBC batchUpdate
Although, this combination seems to be rather non-trivial, on this pls refer to this thread.
I sugest to try this, and if you do not succeed, fall back to pre-fetching from sequence.
据我所知,
getAuto generatedKeys()
也可以用于批量更新。它返回一个包含所有新创建的 id 的 ResultSet - 而不仅仅是单个值。
但这需要在 INSERT 操作期间通过触发器填充 ID。
getAutogeneratedKeys()
will also work with a batch update as far as I remember.It returns a ResultSet with all newly created ids - not just a single value.
But that requires that the ID is populated through a trigger during the INSERT operation.