SELECT LAST

xiaoxiao2021-02-28  34

转载自: http://blog.csdn.net/czd3355/article/details/71302441

首先我先解释以下在在映射文件中的代码是什么意思。

<insert id="insertStudent" parameterType="com.czd.mybatis01.bean.Student"> INSERT stu(name)VALUES (#{name}) <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> </insert> 123456 总体解释:将插入数据的主键返回到 user 对象中。具体解释: SELECT LAST_INSERT_ID():得到刚 insert 进去记录的主键值,只适用与自增主键keyProperty:将查询到主键值设置到 parameterType 指定的对象的那个属性order:SELECT LAST_INSERT_ID() 执行顺序,相对于 insert 语句来说它的执行顺序resultType:指定 SELECTLAST_INSERT_ID() 的结果类型

明白是什么意思后,那么我们要如何才能得到插入数据的主键呢?请看下面代码就知道了

关键代码:

@Test public void main() throws Exception { StudentDao studentDao = new StudentDao(); // 增加 Student student = new Student(); student.setName("b"); studentDao.testInsertStudent(student); } public void testInsertStudent(Student student) throws Exception { SqlSession sqlSession = getSession().openSession(); sqlSession.insert(nameSpace + ".insertStudent", student); sqlSession.commit(); sqlSession.close(); // 得到插入数据的主键并将其打印出来 System.out.println("index: "+student.getId()); } 1234567891011121314151617

打印结果:

其中 index:21 就是我们想要的 id 值了

看到这里不知道有没有读者觉得这不是废话吗?student.getId() 后肯定是得到新插入数据的 id 呀。ok,那么我们来验证一下,把上面映射文件中的这段代码删掉。

<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> 123

打印结果:

从图中我们可以发现程序没有执行 SELECT LAST_INSERT_ID()语句了,并且 index 的值变成了 null,也就是得不到新插入数据的 id 了

到此为止,相信你应该知道怎么使用 SELECT LAST_INSERT_ID() 了吧。

注意点:假如你使用一条INSERT语句插入多个行, LAST_INSERT_ID() 只会返回插入的第一行数据时产生的值。比如我插入了 3 条数据,它们的 id 分别是 21,22,23.那么最后我还是只会得到 21 这个值。

转载请注明原文地址: https://www.6miu.com/read-2650325.html

最新回复(0)