Mybatis中insert 方法總是返回一個(gè)int值 ,這個(gè)值代表的是插入所影響的行數(shù)。 如果id采用自增長策略,自動(dòng)生成的鍵值在 insert 方法執(zhí)行完后可以被設(shè)置到傳入的參數(shù)對(duì)象中。那么我們可以在service中通過傳入的對(duì)象來獲得插入的id值。
mapper.xml文件
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.woniuxy.springbootmybatis.entity.User" useGeneratedKeys="true">
insert into user
( id,user_name,tel
,password,age,create_date
,head_img,dept_id)
values (#{id,jdbcType=INTEGER},#{userName,jdbcType=VARCHAR},#{tel,jdbcType=VARCHAR}
,#{password,jdbcType=VARCHAR},#{age,jdbcType=INTEGER},#{createDate,jdbcType=TIMESTAMP}
,#{headImg,jdbcType=VARCHAR},#{deptId,jdbcType=INTEGER})
</insert>
service代碼文章來源:http://www.zghlxwxcb.cn/news/detail-409110.html
@Override
public int insertSelective(User record) {
int result = userMapper.insertSelective(record);
log.info("當(dāng)前行數(shù)據(jù)的ID為{}",record.getId());
return result;
}
日志文件為:文章來源地址http://www.zghlxwxcb.cn/news/detail-409110.html
2023-04-06 15:45:09.813 INFO 15952 --- [nio-8080-exec-1] c.w.s.service.impl.UserServiceImpl : 當(dāng)前行數(shù)據(jù)的ID為107
到了這里,關(guān)于MyBatis中如何獲取自動(dòng)生成的(主)鍵值的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!