Mybatis+Mysql返回主鍵


 轉載:原文 https://blog.csdn.net/freyaalisa/article/details/75449927

使用MyBatis往MySQL數據庫中插入一條記錄后,成功則返回1,即成功的條數。如果要返回該條記錄的自增主鍵值,在mapper中指定keyProperty屬性,例如:
(1)
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.demo.User">
    insert into user(userName,password,desc) values(#{userName},#{password},#{desc})
</insert>


(2)
<insert id="insert" parameterType="com.demo.User">
<selectKey keyProperty="id" resultType="Long" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
    insert into user(userName,password,desc) values(#{userName},#{password},#{desc})
</insert>

useGeneratedKeys:
取值范圍true|false。默認值是:false。
含義:設置是否使用JDBC的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設置的屬性中。MySQL和SQLServer執行auto-generated key field,因此當數據庫設置好自增長主鍵后,可通過JDBC的getGeneratedKeys方法獲取。但像Oralce等不支持auto-generated key field的數據庫就不能用這種方法獲取主鍵了。

keyProperty:
含義:被設置的目標屬性, MyBatis 會通過 getGeneratedKeys 或者selectKey 子元素設置它的值。默認: 不設置。我們在insert中指定了keyProperty="id",其中id代表插入的User對象的主鍵屬性。

order:
含義:可以被設置為 BEFORE 或 AFTER。如果設置為 BEFORE,那么它會首先選擇主鍵,設置 keyProperty 然后執行插入語句。如果設置為 AFTER,那么先執行插入語句,然后是 selectKey 元素,要想取得正確的key值,應設為AFTER。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM