1.想法
因为业务的需求,需要获得刚插入的那条记录的id
首先考虑到并发的问题,不能直接获取最后一条记录
但是在网上查了一下
SELECT LAST_INSERT_ID()
这个语句是根据上下文的,不会因为并发而出错
2.推荐
但是查了一下官方,官方推荐使用下面这种方式:
在使用sql语句的时候设置useGeneratedKeys=”true”, keyProperty为主键
<insert id="insert" useGeneratedKeys="true" keyProperty="custid" parameterType="com.icekredit.credit.entity.CustID" >
insert into custId (uid)
values (#{uid,jdbcType=VARCHAR})
</insert>
调用:
public int getCustId(CustID custID) {
custIDMapper.insert(custID);
return custID.getCustid();
}
这个时候就会返回插入那条记录的自增id
本文探讨了在并发环境下获取刚插入记录ID的最佳实践。通过对比SELECT LAST_INSERT_ID()与官方推荐的方式,即使用useGeneratedKeys参数来实现这一需求。
838

被折叠的 条评论
为什么被折叠?



