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

懵懂的女人 提交于 2019-11-28 17:38:47

The <selectKey> element is a child of the <insert> element and its content is executed before the main INSERT statement. You can use two approaches.

Fetch the key after you have inserted the record

This approach works depending on your driver. Threading can be a problem with this.

Fetching the key before inserting the record

This approach avoids threading problems but is more work. Example:

<insert id="insert">
  <selectKey keyProperty="myId"
             resultClass="int">
    SELECT nextVal('my_id_seq')
  </selectKey>
  INSERT INTO my
    (myId, foo, bar)
  VALUES
    (#myId#, #foo#, #bar#)
</insert>

On the Java side you can then do

Integer insertedId = (Integer) sqlMap.insert("insert", params)

This should give you the key selected from the my_id_seq sequence.

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);

This way more better than use :

  1. It's simpler;
  2. It have not requested to know sequence name (what usually hidden from postgresql developers).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!