Mybatis自增長id處理


1.使用useGenerateKey

    <insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="personId">
           insert into person(name,pswd) values(#{name},#{pswd})
   </insert> 

或者

   @Mapper
   public interface UserMapper
   {
       @Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
       @Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="user_id")
       void insertUser(User user);
   } 

其中keyProperty對應的屬性為返回對象的字段,keyColumn對應的為表字段

返回新增id在新增對象的id屬性中

這種只能使用在自增長的數據庫中,比如mysql,在oracle中就不行

2.使用select LAST_INSERT_ID()

   <insert id="insert" parameterType="Person">
           <selectKey keyProperty="personId" resultType="long">
               select LAST_INSERT_ID()
           </selectKey>
           insert into person(name,pswd) values(#{name},#{pswd})
   </insert>

LAST_INSERT_ID 是與table無關的,如果向表a插入數據后,再向表b插入數據,LAST_INSERT_ID會改變。

LAST_INSERT_ID是基於Connection的,只要每個線程都使用獨立的Connection對象,LAST_INSERT_ID函數將返回該Connection對AUTO_INCREMENT列最新的insert or update*作生成的第一個record的ID。這個值不能被其它客戶端(Connection)影響,保證了你能夠找回自己的 ID 而不用擔心其它客戶端的活動,而且不需要加鎖。

注意:

使用select last_insert_id()時要注意,當一次插入多條記錄時,只是獲得第一次插入的id值,務必注意。

insert into tb(c1,c2) values (c1value,c2value),(c3value,c4value);select LAST_INSERT_ID();
或者
insert into tb(c1,c2) values (c1value,c2value);
insert into tb(c1,c2) values (c3value,c4value);
select LAST_INSERT_ID();

這兩種情況返回的都是最后插入新增的id,就是上文中新增c3value,c4value的id.

3.使用select @@IDENTITY

   <insert id="insert" parameterType="Person">
           <selectKey keyProperty="personId" resultType="long">
               select @@IDENTITY
           </selectKey>
           insert into person(name,pswd) values(#{name},#{pswd})
   </insert>

@@identity是表示的是最近一次向具有identity屬性(即自增列)的表插入數據時對應的自增列的值,是系統定義的全局變量。一般系統定義的全局變量都是以@@開頭,用戶自定義變量以@開頭。比如有個表A,它的自增列是id,當向A表插入一行數據后,如果插入數據后自增列的值自動增加至101,則通過select @@identity得到的值就是101。使用@@identity的前提是在進行insert操作后,執行select @@identity的時候連接沒有關閉,否則得到的將是NULL值。

4.在MySql中模擬Sequence

這個比較繁瑣,有興趣的可以看[DB][MySql]關於取得自增字段的值、及@@IDENTITY 與並發性問題

參考:

mybatis 操作數據庫的主鍵自增長

mybatis自增長插入id

[DB][MySql]關於取得自增字段的值、及@@IDENTITY 與並發性問題

Mysql 中獲取剛插入的自增長id的值


免責聲明!

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



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