Mybatis 返回主鍵id的實用方法


歡迎關注我的博客。

我們在業務中經常會遇到,執行一個插入sql之后還需要拿到插入后的自增id去做別的事情,這種情況我總結了3種方法。
效果就是你執行完插入語句后,會把自增id自動set到你傳入的實體類中。

1.繼承BaseMapper<T, P>,這個BaseMapper里有個insertSelective()方法,會自動返回主鍵id的值。
這個每個公司可能會有自己不同的BaseMapper生成方法,這里就不做說明了。
詳細說明參考:https://blog.csdn.net/isea533/article/details/41457529

下面兩種方法是比較接地氣的,個人推薦使用:
2.用selectKey標簽
<insert id="insertPerson" parameterType="com.***.domain.Person">
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
SELECT LAST_INSERT_ID() AS ID
</selectKey>
INSERT INTO `Person`
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name!= null">
`name`,
</if>
<if test="sex!= null">
`sex`,
</if>
<if test="className!= null">
`className`,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name!=null">
#{name},
</if>
<if test="sex!=null">
#{sex},
</if>
<if test="className!=null">
#{className},
</if>
</trim>
</insert>
說明:keyProperty:實體類屬性字段
   resultType:返回主鍵的數據類型
   order:執行順序,after表示在執行插入語句之后執行
3.這種方法更簡單
<insert id="insertPerson" useGeneratedKeys="true" keyProperty="id" parameterType="com.***.domain.Person" >
    insert into person (name,sex,className) values( #{name},#{sex},#{className})
</ insert>

或者:直接用@Options()注解也可以做到。就是在你的mapper.java的方法上邊寫上這個注解。
@Insert("insert into person (name,sex,className) values(#{name},#{sex},#{className})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
void insertPerson(Person person);
說明:useGeneratedKeys:是否使用jdbc的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設置的屬性中。
keyProperty:實體類中屬性字段名稱。

備注:以上僅供參考,個人開發總結。希望對你有幫助,讓我們共同進步。
孰能無過,如有錯誤和疑問歡迎留言。

 
        
 


免責聲明!

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



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