MyBatis --执行insert后获取主键

本文介绍了一种在MyBatis中插入记录后立即获取该记录自增长主键的方法,通过设置useGeneratedKeys为true及指定keyProperty,可以在完成插入操作后直接从对象中读取到新生成的主键。

最近做工程时遇到这种情况,刚向数据库插入一条记录,马上需要得到该记录的主键

网上搜索得出如下解决办法

<insert id="insert" parameterType="userInfo" useGeneratedKeys="true" keyProperty="id">
        insert into t_user(user_name,password) values(#{name},#{pswd})
    </insert>

实现层代码如下

        //先添加宠物信息
        CustomerPets customerPets = new CustomerPets();
        
        //customerPets设值
        customerPets.setCustomerId(userId);
        customerPets.setPetName(petName);
        customerPets.setSex(sex);
        customerPets.setPetCategoryId(petCategoryId);
        customerPets.setPetTypeId(petTypeId);
        customerPets.setBirthday(brithday);
        customerPets.setWeight(weight);
        customerPets.setUpdPid(PID);
        customerPets.setUpdUid(userId);
        customerPets.setUseFlag(Constant.UseFlag.USE.getFlag());
        customerPets.setAddUid(userId);
        customerPets.setAddPid(PID);
        
        int success =    customerPetsMapper.insertSelective(customerPets);
        
        if (success == 1) {
        //注意这里取值
        String tmpPetId = customerPets.getPetId();
        }

备注:keyProperty后面的自增长主键,应该与t_user表中主键名称保持一致。

转载于:https://my.oschina.net/u/2312022/blog/649834

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值