mybatis插入或更新語句返回自增逐漸id

因爲公司的表用的是自增id,而不是UUID,所以在好多時候都需要返回新插入的數據的id,所以在網上搜了一些方法,大部分都是用的xml方式來寫的sql,不過本人是用的註解方式,方法比較少,所以寫這篇文章來記錄一下,下面是詳細的方法。

先說註解的方式,我的代碼習慣一般是寫一個dao類(Interface,不是class類),然後寫一個實現類;可能有些人是把sql直接寫在了註解裏邊,但是方法都是一樣的。

直接上代碼

@Mapper
public interface CustomerDao {

    @InsertProvider(type = CustomerProvider.class, method = "saveInfoSql")
    @Options(useGeneratedKeys=true, keyProperty="customerModule.id", keyColumn="id")
    Boolean saveInfo (@Param("customerModule") CustomerModule customerModule);

    @UpdateProvider(type = CustomerProvider.class, method = "updateInfoSql")
    Boolean updateInfo (@Param("customerModule") CustomerModule customerModule);
}

使用註解 @Options 來指定開啓自增主鍵功能,並且指定主鍵名稱。

useGeneratedKeys=true 是開啓改功能;

keyProperty="customerModule.id"  是指定傳入的實體對應表的主鍵的字段;

keyColumn="id" 是指定表內的主鍵字段。

這樣就可以了,在你調用dao方法後直接從你傳入dao方法的實體內就可以拿到對應的id了。

Boolean flag = customerDao.saveInfo(customerModule);
Integer id = customerModule.getId();

例如:

    我傳入的是CustomerModule實體,直接用改實體的get方法getId()就可以。


還有一種是使用xml方式來寫sql,方法如下內容轉自  十七年蟬  鏈接:https://www.cnblogs.com/zhuzhen/p/6894995.html

在開發中碰到用戶註冊的功能需要用到用戶ID,但是用戶ID是數據庫自增生成的,這種情況上網查詢後使用下面的方式配置mybatis的insert語句可以解決

 <insert id="insert" keyProperty="id" useGeneratedKeys="true"
 parameterType="com.demo.domain.User">

 insert into User_t(name,age,addr) values(#{name},#{age},#{addr})
</insert>

注意:數據庫中該表表的主鍵ID是自增的。

通過插入數據的對象可獲得該對象的id。


@Override
    public int insert(User user) {
        int insertNum = Integer.parseInt(userMapper.insert(user) + "");
        Long id = user.getId();//該對象的自增ID
        return insertNum;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章