Mybatis 返回主键id

mybatis 返回主键

对应pojo

@ApiModel("用户数据模型")
public class UserModel {
    @ApiModelProperty("用户ID")
    private Integer id;
    @ApiModelProperty("用户名")
    private String userName;
    @ApiModelProperty("账户")
    private String account;
    @ApiModelProperty("密码")
    private String password;
    @ApiModelProperty("部门")
    private String dept;
    @ApiModelProperty("电话")
    private String phone;
    @ApiModelProperty("创建时间")
    private Date createTime;
}

对应mapper.xml

  <insert id="insert" parameterType="com.proton.screen.model.UserModel" useGeneratedKeys="true" keyProperty="id">
    insert into user_info (user_name, account,
      password, dept, phone, 
      create_time)
    values (#{userName,jdbcType=VARCHAR}, #{account,jdbcType=VARCHAR},
      #{password,jdbcType=VARCHAR}, #{dept,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, 
      #{createTime,jdbcType=TIMESTAMP})
  </insert>
使用
@Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(UserModel info) {
        info.setCreateTime(new Date());
        int affect = userModelMapper.insert(info);
        int newId = info.getId();
        if(affect <= 0) {
            throw new CommonException("添加用户失败");
        }
    }

affect 是影响行数,插入一条数据, 所以affect = 1
newId 是插入数据库后的自增id,所以newId 是对应数据在数据库的id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值