Search code examples
javapostgresqlibatis

Concurrency issues when retriveing Ids of newly inserted rows with ibatis


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.

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>

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.

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

( See also my related question about how to get ibatis to use the INSERT .. RETURING .. statements )


Solution

  • This is definitely wrong. Use:

    select currval('sometable_id_seq')
    

    or better yet:

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

    which will return you inserted id.