mybatis中selectKey有什么用

发布时间:2022-01-25 10:44:43 作者:小新
来源:亿速云 阅读:287

这篇文章给大家分享的是有关mybatis中selectKey有什么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

mybatis的selectKey作用

当我们使用id自增操作Mybatis时,需要返回最新插入的id的话,可以进行如下操作:

<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS ID 
</selectKey>

在insert中添加即可:

<insert id="insert" parameterType="com.pinyougou.pojo.TbGoods" >
    <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
      SELECT LAST_INSERT_ID() AS id
    </selectKey>
    insert into tb_goods (id, seller_id, goods_name,
      default_item_id, audit_status, is_marketable, 
      brand_id, caption, category1_id, 
      category2_id, category3_id, small_pic, 
      price, type_template_id, is_enable_spec, 
      is_delete)
    values (#{id,jdbcType=BIGINT}, #{sellerId,jdbcType=VARCHAR}, #{goodsName,jdbcType=VARCHAR}, 
      #{defaultItemId,jdbcType=BIGINT}, #{auditStatus,jdbcType=VARCHAR}, #{isMarketable,jdbcType=VARCHAR}, 
      #{brandId,jdbcType=BIGINT}, #{caption,jdbcType=VARCHAR}, #{category1Id,jdbcType=BIGINT}, 
      #{category2Id,jdbcType=BIGINT}, #{category3Id,jdbcType=BIGINT}, #{smallPic,jdbcType=VARCHAR}, 
      #{price,jdbcType=DECIMAL}, #{typeTemplateId,jdbcType=BIGINT}, #{isEnableSpec,jdbcType=VARCHAR}, 
      #{isDelete,jdbcType=VARCHAR})
  </insert>

然后操作int newId = goodsMapper.insert(goods.getGoods()); 就能拿到最新加入的ID信息了 

mybatis selectKey 失效问题踩坑

resultType 主键类型

<insert id="insertCheckGroup"  parameterType="com.zyl.pojo.CheckGroup">
        <selectKey resultType="int" keyProperty="id" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into check_group (name) value (#{name});
</insert>

当使用了selectkey时 Dao接口请勿使用@Param 映射注解,会导致selectKey标签失效

int insertCheckGroup(CheckGroup checkGroup);

如果传多个参数需使用@Param时

int insertCheckGroup(@Param("test") CheckGroup checkGroup);

xml标签keyProperty对应主键名称时应加上test.

<insert id="insertCheckGroup"  parameterType="com.zyl.pojo.CheckGroup">
        <selectKey resultType="int" keyProperty="test.id" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into check_group (name) value (#{name});
</insert>

感谢各位的阅读!关于“mybatis中selectKey有什么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. Mybatis有什么用
  2. Mybatis中Mapper接口有什么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis selectkey

上一篇:怎么将Python编译成C语言

下一篇:OpenCV中图像如何实现分割与修复

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》