自增主鍵返回
<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位。
執行順序:
- 先通過UUID()查詢到主鍵,將主鍵輸入到sql語句中
- 執行uuid()順序相對於insert語句之前執行