簡(jiǎn)介
最近在業(yè)務(wù)功能中需要獲取mybatis插入的數(shù)據(jù)并且返回插入數(shù)據(jù)的ID奢啥,去執(zhí)行其他的操作绞佩,說來也很簡(jiǎn)單总放,在正常的insert標(biāo)簽里面加入提供的其他屬性即可實(shí)現(xiàn)倘核,故現(xiàn)在抽時(shí)間整理出來陕见,希望能幫助到需要幫助的朋友
環(huán)境
數(shù)據(jù)庫(kù):mysql(table的id字段設(shè)置為自增)
依賴:jar
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
單條插入返回
DaoMapper接口
Mapper.xml配置
<insert id="insert" useGeneratedKeys="true" keyProperty="releaseDetailsId"
parameterType="com.xxx.CmsReleaseDetails" >
insert into cms_release_details (RELEASE_DETAILS_ID, RELEASE_DETAILS_CODE
)
values (#{releaseDetailsId,jdbcType=INTEGER}, #{releaseDetailsCode,jdbcType=VARCHAR}
)
</insert>
總結(jié):即在普通插入中加入useGeneratedKeys和keyProperty屬性即可秘血,在插入完成后直接獲取該插入實(shí)體封裝的ID即可獲取到參數(shù)。
批量插入
批量插入DaoMapper接口
<insert id="insertBatch" useGeneratedKeys="true"
keyProperty="releaseDetailsId" keyColumn="RELEASE_DETAILS_ID"
parameterType="java.util.List" >
insert into cms_release_details (
RELEASE_DETAILS_ID,RELEASE_DETAILS_CODE) values
<foreach collection="list" item="item" index="index" separator="," >
( #{item.releaseDetailsId,jdbcType=INTEGER},
#{item.releaseDetailsCode,jdbcType=VARCHAR})
</foreach>
</insert>
但此時(shí)插入?yún)s報(bào)異常:
nested exception is org.apache.ibatis.binding.BindingException:
Parameter ' releaseDetailsId ' not found.
Available parameters are [list, collection]
后查證資料评甜,批量插入返回ID報(bào)錯(cuò)bug在mybatis.3.3.1才被修復(fù)灰粮,故將mybatis升級(jí)為3.3.1,spring-mybatis版本不做處理忍坷,重啟后正常插入且成功返回正確id
總結(jié)
其實(shí)批量插入返回ID和單條插入返回ID沒有什么差別粘舟,首先還是要確定原本不返回值的插入是否成功熔脂,然后再做進(jìn)一步操作,循序漸進(jìn)
參考資料:
https://github.com/mybatis/mybatis-3/pull/324
https://github.com/abel533/mybatis-3/blob/master/src/main/java/org/apache/ibatis/executor/keygen/Jdbc3KeyGenerator.java