需求:使用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