您的位置:首页 > 其它

mybatis中Insert方法返回主键的功能

2017-11-12 21:58 501 查看
由于业务需求,利用mybatis插入记录的时候,它默认返回的是插入几条记录,因为我的表设计是主键自增长,而且我需要获得我插入这条记录的id,去插入其他表。于是可以这么写:

<insert id="insertSelective" useGeneratedKeys="true" keyProperty="laId"
parameterType="com.tracy.gd.domain.LendingApply">
insert into gd_lending_apply
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="laId != null">
la_id,
</if>
<if test="laUserId != null">
la_user_id,
</if>
<if test="laCptId != null">
la_cpt_id,
</if>
<if test="laReason != null">
la_reason,
</if>
<if test="laLendTime != null">
la_lend_time,
</if>
<if test="laReturnTime != null">
la_return_time,
</if>
<if test="laCommons != null">
la_commons,
</if>
<if test="laLocation != null">
la_location,
</if>
<if test="laIsCheck != null">
la_is_check,
</if>
<if test="attribute1 != null">
attribute1,
</if>
<if test="attribute2 != null">
attribute2,
</if>
<if test="attribute3 != null">
attribute3,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="laId != null">
#{laId,jdbcType=INTEGER},
</if>
<if test="laUserId != null">
#{laUserId,jdbcType=INTEGER},
</if>
<if test="laCptId != null">
#{laCptId,jdbcType=INTEGER},
</if>
<if test="laReason != null">
#{laReason,jdbcType=VARCHAR},
</if>
<if test="laLendTime != null">
#{laLendTime,jdbcType=TIMESTAMP},
</if>
<if test="laReturnTime != null">
#{laReturnTime,jdbcType=TIMESTAMP},
</if>
<if test="laCommons != null">
#{laCommons,jdbcType=VARCHAR},
</if>
<if test="laLocation != null">
#{laLocation,jdbcType=VARCHAR},
</if>
<if test="laIsCheck != null">
#{laIsCheck,jdbcType=VARCHAR},
</if>
<if test="attribute1 != null">
#{attribute1,jdbcType=VARCHAR},
</if>
<if test="attribute2 != null">
#{attribute2,jdbcType=VARCHAR},
</if>
<if test="attribute3 != null">
#{attribute3,jdbcType=VARCHAR},
</if>
</trim>
</insert>

这样在调用这个方法的Service的时候,传入一个未设置id的对象,他就会把主键返回到这个实体集相应的属性上,即可通过getter方法取到想要的东西。
useGeneratedKeys="true" keyProperty="laId"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: