2

我正在使用 iBatis/Java 和 Postgres 8.3。当我在 ibatis 中插入时,我需要返回 id。
我使用下表来描述我的问题:通过运行 create 语句自动生成
CREATE TABLE sometable ( id serial NOT NULL, somefield VARCHAR(10) );
序列。sometable_id_seq

目前我使用以下 sql 映射:

<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。
我怀疑这是否适用于许多并发插入。

这会导致问题吗?就像返回错误插入的 id 一样?

(另请参阅我有关如何让 ibatis 使用 INSERT .. RETUING .. 语句的相关问题)

4

3 回答 3

2

这绝对是错误的。采用:

select currval('sometable_id_seq')

或者更好:

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

这将返回您插入的 id。

于 2009-11-20T13:22:03.580 回答
0

这是一个简单的例子:

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

在 Java 代码中:

Integer id = (Integer) executor.queryForObject("addObject", object);
object.setId(id);
于 2009-12-03T20:08:34.693 回答
0

我有另一个想法。ibatis调用 insert 方法委托 Class: com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate,with the code:

 try {
      trans = autoStartTransaction(sessionScope, autoStart, trans);

      SelectKeyStatement selectKeyStatement = null;
      if (ms instanceof InsertStatement) {
        selectKeyStatement = ((InsertStatement) ms).getSelectKeyStatement();
      }

      // Here we get the old value for the key property. We'll want it later if for some reason the
      // insert fails.
      Object oldKeyValue = null;
      String keyProperty = null;
      boolean resetKeyValueOnFailure = false;
      if (selectKeyStatement != null && !selectKeyStatement.isRunAfterSQL()) {
        keyProperty = selectKeyStatement.getKeyProperty();
        oldKeyValue = PROBE.getObject(param, keyProperty);
        generatedKey = executeSelectKey(sessionScope, trans, ms, param);
        resetKeyValueOnFailure = true;
      }

      StatementScope statementScope = beginStatementScope(sessionScope, ms);
      try {
        ms.executeUpdate(statementScope, trans, param);
      }catch (SQLException e){
        // uh-oh, the insert failed, so if we set the reset flag earlier, we'll put the old value
        // back...
        if(resetKeyValueOnFailure) PROBE.setObject(param, keyProperty, oldKeyValue);
        // ...and still throw the exception.
        throw e;
      } finally {
        endStatementScope(statementScope);
      }

      if (selectKeyStatement != null && selectKeyStatement.isRunAfterSQL()) {
        generatedKey = executeSelectKey(sessionScope, trans, ms, param);
      }

      autoCommitTransaction(sessionScope, autoStart);
    } finally {
      autoEndTransaction(sessionScope, autoStart);
    }

您可以看到 insert 和 select 运算符位于Transaction中。所以我认为插入方法没有并发问题。

于 2012-08-19T12:12:52.810 回答