SELECT LAST_INSERT_ID()总是返回1或者0

今天在做项目的时候使用到了SELECT LAST_INSERT_ID(),发现每次返回的结果都是1,我原来的sql语句比较长,下面用个事例演示一下。

@Insert("INSERT INTO student(name,phone,address)VALUES(#{name},#{phone},#{address})")
@SelectKey(keyProperty = "id", keyColumn = "id", resultType = int.class, before = false, statement = "select last_insert_id()")
int insert(Student student);

执行insert()方法,期望是每次返回上一次插入的数据的主键id,然而每次都返回1,经过一番检查后,发现"select last_insert_id()"已经执行了但是并不是这个方法的返回值,insert()方法的返回值是指执行完insert语句后影响数据库的行数,所以只有0或者1(即失败或者成功),而"select last_insert_id()"语句的结果被封装到了student对象中了,所以执行完sql语句后可以通过student.getId();获得。

发布了167 篇原创文章 · 获赞 230 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_39240270/article/details/93461318