“SELECT LAST_INSERT_ID 总是为1”
问题
问题是发生在从 ibatis 升级到 mybatis 出现的,代码中使用 SELECT LAST_INSERT_ID 获取自增 id,原来在 ibatis 好用的代码,升级到了 mybatis 就总是返回 1 了。
linkedkeeper_sequence 表结构如下:
CREATE TABLE `linkedkeeper_sequence` (
`seq_name` varchar(200) NOT NULL,
`current_value` bigint(20) NOT NULL,
`_increment` int(4) NOT NULL,
PRIMARY KEY (`seq_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
ibatis 中获取自增 id 的 xml:
<insert timeout="30" id="update" parameterClass="java.lang.String">
UPDATE linkedkeeper_sequence
SET
current_value = LAST_INSERT_ID(current_value + _increment)
WHERE
seq_name = #seqname#
<selectKey resultClass="long">
<![CDATA[SELECT LAST_INSERT_ID() ]]>
</selectKey>
</insert>
Dao 的代码:
public long getSeq(final String seqName) throws Exception {
return insert("Seq.update", seqName);
}
第一次修改成 mybatis 的 xml,但总是返回 1。
<insert timeout="30" id="update" parameterType="java.lang.String">
UPDATE linkedkeeper_sequence
SET
current_value = LAST_INSERT_ID(current_value + _increment)
WHERE
seq_name = #{seqname}
<selectKey resultClass="long">
<![CDATA[SELECT LAST_INSERT_ID() ]]>
</selectKey>
</insert>
原因
在 mybatis 中,insert 之后返回的是 1 是影响的行数,并不是自增 id。
This chapter requires login to view full content. You are viewing a preview.
Login to View Full Content