Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto return ids on Inserts with Ibatis ( with RETURNING keyword )

Tags:

People also ask

How do I get my last inserted ID in MyBatis?

I thought statement written here 'SELECT LAST_INSERT_ID() as id' should return id of last inserted record but I am getting always 1 after inserting the record. int id = fileAttachmentMapper. insertSelective(fileAttachment); I am getting value of Id always 1 when new record is inserted.

How do I use Java MyBatis?

MYBATIS is a persistence framework that automates the mapping among SQL databases and objects in Java, . NET, and Ruby on Rails. MYBATIS makes it easier to build better database oriented-applications more quickly and with less code.

Does MyBatis use prepared statement?

MyBatis does four main things: It executes SQL safely and abstracts away all the intricacies of JDBC. It maps parameter objects to JDBC prepared statement parameters. It maps rows in JDBC result sets to objects.

What is mapper in MyBatis?

Mapper XML is an important file in MyBatis, which contains a set of statements to configure various SQL statements such as select, insert, update, and delete. These statements are known as Mapped Statements or Mapped SQL Statements. All the statements have unique id.


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. ( discussed in this question )

I'd like to use the following statement with ibatis:
INSERT INTO sometable ( somefield ) VALUES ( #value# ) RETURNING id;

But when i try to use it within a <insert> sqlMap ibatis does not return the id. It seems to need the <selectKey> tag.

So here comes the question:

How can i use the above statement with ibatis?