MyBatis的插入后获得主键的方式
生活随笔
收集整理的這篇文章主要介紹了
MyBatis的插入后获得主键的方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求:
使用MyBatis往MySQL數據庫中插入一條記錄后,需要返回該條記錄的自增主鍵值。
方法:
在mapper中指定keyProperty屬性,示例如下:
<insert id="insertUser" useGeneratedKeys="true" keyProperty="userId" parameterType="cn.stu.entity.UserEntity">insert?into?user(userName,password,comment)??values(#{userName},#{password},#{comment})??
</insert>
注意:
此處可能會有坑:如果在<insert>的右邊尖括號之后有空格,在啟動時可能會報:元素類型 "insert" 必須后跟屬性規范 ">" 或 "/>",并且,在作新增操作時會一直增不進去而報SQL語法錯誤,碰到這類問題就把<insert>標簽整體在敲一邊就可以了
如上所示,我們在insert中指定了keyProperty="userId",其中userId代表插入的User對象的主鍵屬性。
User.java
public?class?User?{??private?int?userId;??private?String?userName;??private?String?password;??private?String?comment;??//setter?and?getter??
}??
?UserDao.java
public?interface?UserDao?{??public?int?insertAndGetId(User?user);??}??
?測試:
Java代碼??
User?user?=?new?User();??
user.setUserName("chenzhou");??
user.setPassword("xxxx");??
user.setComment("測試插入數據返回主鍵功能");??System.out.println("插入前主鍵為:"+user.getUserId());??
userDao.insertAndGetId(user);//插入操作??
System.out.println("插入后主鍵為:"+user.getUserId());??
?輸出:
插入前主鍵為:0??
插入后主鍵為:15??
查詢數據庫:
如上所示,剛剛插入的記錄主鍵id為15
總結:
用了這個useGenerateKeys="true"后,不用再在寫一句關于select的SQL(降低數據庫的壓力)而直接能夠得到剛剛插進去的那個主鍵,但是——這個屬性只能用在主鍵能自增長的數據庫里面比如MySQL可以用,但是oracle就不能用了!
對于oracle返回自增主鍵(oracle序列)如下:
- keyProperty:將查詢到主鍵值設置到parameterType指定的對象的哪個屬性
- order:相對于insert語句來說它的執行順序,只要不是自增主鍵,那么就設置為before
- resultType:指定返回的結果類型
?
<insert id="insert" parameterType="cn.entity.Userinfo">?<selectKey keyProperty="userId" resultType="java.lang.String" order="before">select seq.nextval from dual</seledtKey>insert intouserinfo (userId,userName,userpass,usertype,address)?values(#{userId},#{userName},#{userPass},#{userType},#{address})</insert>
?
總結
以上是生活随笔為你收集整理的MyBatis的插入后获得主键的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022-2028年中国数字化制造产业研
- 下一篇: 2022-2028年中国数字化档案加工行