Mybatis+Mysql插入數據庫返回自增主鍵id值的三種方法
阿新 • • 發佈:2018-03-21
文章 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- /**
- * 插入數據庫並返回主鍵id
- * @param batch
- * @return
- */
- Integer insertBatchReturnId(Batch batch);
xml的sql語句寫法
記得加上useGeneratedKeys和keyProperty配置即可,前者是指設置是否使用jdbc的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設置的屬性中,後者即實體類主鍵字段(並且大小寫要對應上)
[html] view plain copy
- <insert id="insertBatchReturnId" useGeneratedKeys="true" keyProperty="id" parameterType="org.uz.dxt.model.bankbase.Batch" >
- insert into t_batch (
- batchCode,
- bankCode,
- bizType,
- companyCode,
- wtEndDate,
- wtDate,
- contractId,
- totalCount,
- totalBase,
- handCode)
- values
- ( #{batchcode},
- #{bankcode},
- #{biztype},
- #{companycode},
- #{wtenddate},
- #{wtdate},
- #{contractid},
- #{totalcount},
- #{totalbase},
- #{handCode})
- </insert>
controller的實際應用:使用方法id會直接將映射到參數的實體上使用時直接使用參數的實體get獲取值
[java] view plain copy
- batchService.insertBatch(param);//實體
- idlist.add(param.getId());
第三種:sql語句使用<selectKey>獲取自增逐漸id
[html] view plain copy
- <insert id="add" parameterType="EStudent">
- // 下面是SQLServer獲取最近一次插入記錄的主鍵值的方式
- <selectKey resultType="_long" keyProperty="id" order="AFTER">
- select @@IDENTITY as id
- </selectKey>
- insert into TStudent(name, age) values(#{name}, #{age})
- </insert>
使用用法同上
這裏推薦使用第一種和第二種中方法
第三種方法對oracl額外的配置
controller的實際應用:使用方法id會直接將映射到參數的實體上使用時直接使用參數的實體get獲取值
Mybatis+Mysql插入數據庫返回自增主鍵id值的三種方法