views:

300

answers:

2

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 )

+1  A: 

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.

depesz
So you think it will cause problems. My other question is about howto get the INSERT INTO .. RETURNING .. statement into ibatis (Since i cant post a link in here i added it at the end of the question)
Christoph
Of course it will. try yourself with 2 connections from psql.as for ibatis - i have no idea what it is, but it looks java-related - which means i can't help.
depesz
A: 

Here is simple example:

<statement id="addObject"
     parameterClass="test.Object"
     resultClass="int">
     INSERT INTO objects(expression, meta, title,
     usersid)
     VALUES (#expression#, #meta#, #title#, #usersId#)
     RETURNING id
</statement>

And in Java code:

Integer id = (Integer) executor.queryForObject("addObject", object);
object.setId(id);
leonidv