使用ibatis检索新插入的ID时的并发问题 [英] Concurrency issues when retriveing Ids of newly inserted rows with ibatis

查看:126
本文介绍了使用ibatis检索新插入的ID时的并发问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iBatis / Java和Postgres 8.3。
当我在ibatis中插入时,我需要返回id。

我使用下表来描述我的问题:

CREATE TABLE sometable (id serial NOT NULL,somefield VARCHAR(10));

序列 sometable_id_seq 通过运行create语句自动生成。

I'm using iBatis/Java and Postgres 8.3. When I do an insert in ibatis i need the id returned.
I use the following table for describing my question:
CREATE TABLE sometable ( id serial NOT NULL, somefield VARCHAR(10) );
The Sequence sometable_id_seq gets autogenerated by running the create statement.

目前我使用以下sql地图:

At the moment i use the following sql map:

<insert id="insertValue" parameterClass="string" >
 INSERT INTO sometable ( somefield ) VALUES ( #value# );
 <selectKey keyProperty="id" resultClass="int">
  SELECT last_value AS id FROM sometable_id_seq
 </selectKey>
</insert>

这似乎是检索新插入的id的ibatis方式。 Ibatis首先运行一个INSERT语句,然后它询问序列的最后一个id。

我怀疑这可以用于许多并发插入。

It seems this is the ibatis way of retrieving the newly inserted id. Ibatis first runs a INSERT statement and afterwards it asks the sequence for the last id.
I have doubts that this will work with many concurrent inserts.

这会引起问题吗?比如返回错误插入的id?

Could this cause problems? Like returning the id of the wrong insert?

(另请参阅我关于如何让ibatis使用INSERT .. RETURING ..语句

推荐答案

这绝对是错误的。使用:

This is definitely wrong. Use:

select currval('sometable_id_seq')

或更好:

INSERT INTO sometable ( somefield ) VALUES ( #value# ) returning id

将返回你插入的id。

这篇关于使用ibatis检索新插入的ID时的并发问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆