1. 程式人生 > >Mybatis+Mysql插入數據庫返回自增主鍵id值的三種方法

Mybatis+Mysql插入數據庫返回自增主鍵id值的三種方法

文章 param mysql int sta source nbsp 通用 映射

一、場景:

插入數據庫的值需要立即得到返回的主鍵id進行下一步程序操作

二、解決方法:

第一種:使用通用mapper的插入方法

Mapper.insertSelective(record);

此方法:插入一條數據,只插入不為null的字段,不會影響有默認值的字段
支持Oracle序列,UUID,類似Mysql的INDENTITY自動增長(自動回寫)
優先使用傳入的參數值,參數值空時,才會使用序列、UUID,自動增長


controller的實際應用:使用方法id會直接將映射到參數的實體上使用時直接使用參數的實體get獲取值

通用mapper相關配置查看其它文章 http://blog.csdn.net/isea533/article/details/41457529

第二種:編寫sql語句

dao層方法:

[java] view plain copy
  1. /**
  2. * 插入數據庫並返回主鍵id
  3. * @param batch
  4. * @return
  5. */
  6. Integer insertBatchReturnId(Batch batch);

xml的sql語句寫法

記得加上useGeneratedKeys和keyProperty配置即可,前者是指設置是否使用jdbc的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設置的屬性中,後者即實體類主鍵字段(並且大小寫要對應上)

[html] view plain copy
  1. <insert id="insertBatchReturnId" useGeneratedKeys="true" keyProperty="id" parameterType="org.uz.dxt.model.bankbase.Batch" >
  2. insert into t_batch (
  3. batchCode,
  4. bankCode,
  5. bizType,
  6. companyCode,
  7. wtEndDate,
  8. wtDate,
  9. contractId,
  10. totalCount,
  11. totalBase,
  12. handCode)
  13. values
  14. ( #{batchcode},
  15. #{bankcode},
  16. #{biztype},
  17. #{companycode},
  18. #{wtenddate},
  19. #{wtdate},
  20. #{contractid},
  21. #{totalcount},
  22. #{totalbase},
  23. #{handCode})
  24. </insert>

controller的實際應用:使用方法id會直接將映射到參數的實體上使用時直接使用參數的實體get獲取值

[java] view plain copy
  1. batchService.insertBatch(param);//實體
  2. idlist.add(param.getId());

第三種:sql語句使用<selectKey>獲取自增逐漸id


[html] view plain copy
  1. <insert id="add" parameterType="EStudent">
  2. // 下面是SQLServer獲取最近一次插入記錄的主鍵值的方式
  3. <selectKey resultType="_long" keyProperty="id" order="AFTER">
  4. select @@IDENTITY as id
  5. </selectKey>
  6. insert into TStudent(name, age) values(#{name}, #{age})
  7. </insert>

使用用法同上

這裏推薦使用第一種和第二種中方法

第三種方法對oracl額外的配置

controller的實際應用:使用方法id會直接將映射到參數的實體上使用時直接使用參數的實體get獲取值

Mybatis+Mysql插入數據庫返回自增主鍵id值的三種方法