Mybatis配置useGeneratedKeys="true" keyProperty="id"的作用


有時候在開發中需要向表中插入自增ID,這個時候領域模型如果想要獲取該ID的值,就需要在相應的mapper文件中添加useGeneratedKeys="true" keyProperty="id"。

MyBatis如何獲取插入記錄的自增長字段值:

 

第一步:

 

    在Mybatis Mapper文件中添加屬性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java對象的屬性名!

<insert id="insert" parameterType="Spares" 
        useGeneratedKeys="true" keyProperty="id">
        insert into spares(spares_id,spares_name,
            spares_type_id,spares_spec)
        values(#{id},#{name},#{typeId},#{spec})
    </insert>

 

第二步:

    Mybatis執行完插入語句后,自動將自增長值賦值給對象Spares的屬性id。因此,可通過Spares對應的getter方法獲取!

復制代碼
    /**
     * 新增備件
     * @author hellostory
     * @param spares
     * @return
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public JsonResponse insert(Spares spares) {
        int count = sparesService.insert(spares);      //count>0 表示成功
        System.out.println( "剛剛插入記錄的主鍵自增長值為:" + spares.getId());
復制代碼

 

 如果沒有useGeneratedKeys="true"和keyProperty="id",下面 insert 之后的 user.getId() 是無法獲取 id 值的public void insert(User user) {      int count = userMapper.insert(user);     System.out.println("共插入" + count + "條記錄!"  + "\n剛剛插入記錄的主鍵自增長值為:" + user.getId()); }

 


免責聲明!

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



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