Mybatis使用SELECT LAST_INSERT_ID()返回0问题避坑
SELECT LAST_INSERT_ID()用于返回最后插入表中数据的主键值,一般用于表主键自增且需要用到该自增的主键值的情况
<insert id="insertOrder" parameterType="com.example.bobosapce.Entity.WorkOrder">
INSERT INTO WORKORDER(administratorid,category,createtime,userid,status) VALUES(#{administratorid},#{category},#{createtime},#{userid},2)
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="orderid">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
- parameterType:对应方法传入的参数类型,这里为实体类
- <SelectKey>标签即用来实现SELECT LAST_INSERT_ID()
- resultType:主键类型
- order:AFTER 表示 SELECT LAST_INSERT_ID() 在insert执行之后执行,多用与自增主键
BEFORE 表示 SELECT LAST_INSERT_ID() 在insert执行之前执行,这样的话就拿不到主键了,适合那种主键不是自增的类型 - keyProperty:对应传入参数的主键,SELECT LAST_INSERT_ID()执行后会将得到的主键值存入实体类对应的主键属性名
附注解版:
@Insert("INSERT INTO WORKORDER(administratorid,category,createtime,userid,status) VALUES(#{administratorid},#{category},#{createtime},#{userid},2)")
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "orderid", resultType = Integer.class, before = false)
int insertOrder(WorkOrder workOrder);
踩坑!
- 出于习惯,Mapper中方法无论单参还是多参,都会加上@Param注解,在网上查阅相关博客得到在使用<SelectKey>标签情况下,加上@Param注解会使<SelectKey>失效的结论,导致每次都会得到新增的主键值为0的情况,所以单参情况下去掉@Param注解可以解决问题,但是经过多次实测,发现@Param并不是不能存在,只要占位符中参数名和keyProperty与@Param完全匹配即可,以注解形式为例:
@Insert("INSERT INTO WORKORDER(administratorid,category,createtime,userid,status) VALUES(#{workorder.administratorid},#{workorder.category},#{workorder.createtime},#{workorder.userid},2)")//占位符对应@Param
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "workorder.orderid", resultType = Integer.class, before = false)//keyProperty对应@Param
int insertOrder(@Param("workorder")WorkOrder workorder);
- xml配置同理