MyBatis中如何获取自动生成的(主)键值

Mybatis中insert 方法总是返回一个int值 ,这个值代表的是插入所影响的行数。 如果id采用自增长策略,自动生成的键值在 insert 方法执行完后可以被设置到传入的参数对象中。那么我们可以在service中通过传入的对象来获得插入的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代码

 @Override
    public int insertSelective(User record) {
        int result = userMapper.insertSelective(record);
        log.info("当前行数据的ID为{}",record.getId());
        return result;
    }

日志文件为:

2023-04-06 15:45:09.813  INFO 15952 --- [nio-8080-exec-1] c.w.s.service.impl.UserServiceImpl       : 当前行数据的ID为107

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值