Mybatis自增主鍵返回與非自增主鍵返回

自增主鍵返回

<insert id="zizenginsertToStudent" parameterType="com.nsu.mybatis.practice.Student">

<!-- 
  將插入數據的主鍵返回,返回到student2對象中
  SELECT LAST_INSERT_ID():得到剛insert進去記錄的主鍵值,只適用於自增主鍵

  keyProperty:將查詢到的主鍵值設置到parameterType指定的對象的哪個屬性
  order:SELECT LAST_INSERT_ID()執行順序,想對於insert語句來說它的執行順序
   resultType:指定 SELECT LAST_INSERT_ID()返回的結果類型
 -->
  <selectKey keyProperty="sid" order="AFTER" resultType="java.lang.Integer">
  SELECT LAST_INSERT_ID()
  </selectKey>
     INSERT INTO student(sname,sex) VALUES(#{sname},#{sex})
 </insert>
      String resource = "mybatis-config.xml";
      SqlSession sqlSession = null;

      Student student=new Student();

      InputStream is = Resources.getResourceAsStream(resource);

         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
          sqlSession = factory.openSession();

      Student student2=new Student();
      student2.setSex("na");
      student2.setSname("yy");

        sqlSession.insert("test.zizenginsertToStudent", student2);

        sqlSession.commit();

        System.out.println(student2.getSid());
        sqlSession.close();

非自增主鍵返回

使用mysql的uuid()函數生成主鍵,需要修改表中di字段類型爲String,長度設置成35位。
執行順序:

  1. 先通過UUID()查詢到主鍵,將主鍵輸入到sql語句中
  2. 執行uuid()順序相對於insert語句之前執行

這裏寫圖片描述

發佈了82 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章