mybatis插入数据并获取主键值

有时候我们的主键是自增的,但是我们想要在插入一条数据以后获取这条数据的主键值,而我们知道,mybatis执行完插入操作以后返回的是生效的记录数。那如何才能获取这个主键值呢。

1.在配置文件mapper.xml中加入如下语句。

     <insert id="insertSelectiveRePk" parameterType="com.xdx.entity.TMenu"
useGeneratedKeys="true" keyProperty="menuId" keyColumn="menu_id">
insert into t_menu
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="menuId != null">
menu_id,
</if>
<if test="menuName != null">
menu_name,
</if>
<if test="menuType != null">
menu_type,
</if>
<if test="menuLevel != null">
menu_level,
</if>
<if test="menuIcon != null">
menu_icon,
</if>
<if test="menuSrc != null">
menu_src,
</if>
<if test="rMenuId != null">
r_menu_id,
</if>
<if test="pMenuId != null">
p_menu_id,
</if>
<if test="menuIntro != null">
menu_intro,
</if>
<if test="priority1 != null">
priority1,
</if>
<if test="priority2 != null">
priority2,
</if>
<if test="priority3 != null">
priority3,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
<if test="isDel != null">
is_del,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="menuId != null">
#{menuId,jdbcType=INTEGER},
</if>
<if test="menuName != null">
#{menuName,jdbcType=VARCHAR},
</if>
<if test="menuType != null">
#{menuType,jdbcType=INTEGER},
</if>
<if test="menuLevel != null">
#{menuLevel,jdbcType=INTEGER},
</if>
<if test="menuIcon != null">
#{menuIcon,jdbcType=VARCHAR},
</if>
<if test="menuSrc != null">
#{menuSrc,jdbcType=VARCHAR},
</if>
<if test="rMenuId != null">
#{rMenuId,jdbcType=INTEGER},
</if>
<if test="pMenuId != null">
#{pMenuId,jdbcType=INTEGER},
</if>
<if test="menuIntro != null">
#{menuIntro,jdbcType=VARCHAR},
</if>
<if test="priority1 != null">
#{priority1,jdbcType=INTEGER},
</if>
<if test="priority2 != null">
#{priority2,jdbcType=INTEGER},
</if>
<if test="priority3 != null">
#{priority3,jdbcType=INTEGER},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="isDel != null">
#{isDel,jdbcType=INTEGER},
</if>
</trim>
</insert>

注意第二行的几句代码:useGeneratedKeys="true" keyProperty="menuId" keyColumn="menu_id"

useGeneratedKeys="true" :使用自增的主键

keyProperty="menuId"  :主键对应的java实体的成员

keyColumn="menu_id" :主键在数据库中的列名

2.在插入后就可以直接获取主键值了,代码如下

baseDao.addT("TMenuMapper.insertSelectiveRePk", menu);//插入
int key=menu.getMenuId();//直接获取主键

其中menu就是我们要保存的实体。

上一篇:combo参数配置_手册


下一篇:js中判断对象数据类型的方法