SELECT LAST_INSERT_ID() 的使用和注意事項

轉載自:
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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 總體解釋:將插入數據的主鍵返回到 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());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

打印結果:

這裏寫圖片描述

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

看到這裏不知道有沒有讀者覺得這不是廢話嗎?student.getId() 後肯定是得到新插入數據的 id 呀。ok,那麼我們來驗證一下,把上面映射文件中的這段代碼刪掉。

 <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
    SELECT LAST_INSERT_ID()
</selectKey>
  • 1
  • 2
  • 3

打印結果:

這裏寫圖片描述

從圖中我們可以發現程序沒有執行 SELECT LAST_INSERT_ID()語句了,並且 index 的值變成了 null,也就是得不到新插入數據的 id 了

到此爲止,相信你應該知道怎麼使用 SELECT LAST_INSERT_ID() 了吧。

注意點:假如你使用一條INSERT語句插入多個行, LAST_INSERT_ID() 只會返回插入的第一行數據時產生的值。比如我插入了 3 條數據,它們的 id 分別是 21,22,23.那麼最後我還是隻會得到 21 這個值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章