MyBatis+MySQL 进行insert之后可获取主键ID

需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。

方法:在mapper中指定keyProperty属性,示例如下:

<insert id="addCoupon" parameterType="com.datebook.entity.Coupon" useGeneratedKeys="true" keyProperty="id">
    insert into coupon
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="user_id != null" >
        user_id,
      </if>
      <if test="type != null" >
        type,
      </if>
      <if test="denomination != null">
        denomination,
      </if>
      <if test="campaign_id != null">
        campaign_id,
      </if>
      <if test="expire_date != null">
        expire_date,
      </if>
      <if test="create_time != null" >
        create_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="user_id != null" >
        #{user_id,jdbcType=INTEGER},
      </if>
      <if test="type != null" >
        #{type,jdbcType=INTEGER},
      </if>
      <if test="denomination != null">
        #{denomination, jdbcType=INTEGER},
      </if>
      <if test="campaign_id != null">
        #{campaign_id, jdbcType=INTEGER},
      </if> 
      <if test="expire_date != null">
        #{expire_date, jdbcType=TIMESTAMP},
      </if>      
      <if test="create_time != null" >
        #{create_time, jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>

如上所示,我们在insert中指定了keyProperty=”id”,其中id代表插入的对象的主键属性。
(以下为其他方法测试数据,非上表内容。只是为了演示效果)

User user = new User();  
user.setUserName("chenzhou");  
user.setPassword("xxxx");  
user.setComment("测试插入数据返回主键功能");  

System.out.println("插入前主键为:"+user.getId());  
userDao.insertAndGetId(user);//插入操作  
System.out.println("插入后主键为:"+user.getId());  

输出:

插入前主键为:0  
插入后主键为:100  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值