mybatis获取刚刚插入到数据库的数据的id

很多时候,我们需要获取到刚刚插入到数据库的数据的id是什么,这里的id可能有两种情况,一种是自增长的id,另外一种情况是用户自定义的id,例如生成的uuid。

思路:insert完成之后再去查询得到id,这样显然不行,很可能获取到的id不是自己想要的那条数据的id,只有在insert的过程中获取到id,再将其包装在结果集中一起返回,这样才能万无一失,保证返回id的准确性。

实现方法:mybatis的selectKey标签配合sql语句就可以实现这一需求;或者是在insert标签中加入useGeneratedKeys和keyProperty属性也可以(useGeneratedKeys是使用生成的主键的意思)。

写法如下:

第一种写法:

第二种写法:

第一种写法详解:

keyProperty属性表示要查询的主键的名字,就是主键字段对应实体类的属性。

order属性有两个值,即after,before;after表示在insert之后执行SELECT LAST_INSERT_ID(),一般用于主键自增时,得到的就是自增长生成的id,而before表示在insert之前执行SELECT LAST_INSERT_ID(),一般用于非自增主键,得到的是传入的对象中主键的值,一般是用户生成的uuid。

resultType属性表示主键的类型,一般要么是Integer,要么是String

将该selectKey标签的内容放入insert标签语句中就ok了,例如:

<insert id="insertSelective" parameterType="com.rkxch.studypaper.po.StoryComments">
      
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    
    insert into story_comments
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="storyId != null">
        story_id,
      </if>
      <if test="userId != null">
        user_id,
      </if>
      <if test="isDisplayName != null">
        is_display_name,
      </if>
      <if test="isSupport != null">
        is_support,
      </if>
      <if test="likeCount != null">
        like_count,
      </if>
      <if test="auditUserId != null">
        audit_user_id,
      </if>
      <if test="auditStatus != null">
        audit_status,
      </if>
      <if test="auditTime != null">
        audit_time,
      </if>
      <if test="dislikeCount != null">
        dislike_count,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="updateTime != null">
        update_time,
      </if>
      <if test="commentsContent != null">
        comments_content,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="storyId != null">
        #{storyId,jdbcType=INTEGER},
      </if>
      <if test="userId != null">
        #{userId,jdbcType=INTEGER},
      </if>
      <if test="isDisplayName != null">
        #{isDisplayName,jdbcType=INTEGER},
      </if>
      <if test="isSupport != null">
        #{isSupport,jdbcType=INTEGER},
      </if>
      <if test="likeCount != null">
        #{likeCount,jdbcType=INTEGER},
      </if>
      <if test="auditUserId != null">
        #{auditUserId,jdbcType=INTEGER},
      </if>
      <if test="auditStatus != null">
        #{auditStatus,jdbcType=INTEGER},
      </if>
      <if test="auditTime != null">
        #{auditTime,jdbcType=TIMESTAMP},
      </if>
      <if test="dislikeCount != null">
        #{dislikeCount,jdbcType=INTEGER},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="commentsContent != null">
        #{commentsContent,jdbcType=LONGVARCHAR},
      </if>
    </trim>
  </insert>

运行效果:

笔者的这个项目,数据库的表结构主键都是自增长,所以selectKey标签中order属性必须是AFTER,而且是大写。

如果,将order属性改成BEFORE会怎样呢?

运行效果如下:

这里查询的主键id是对象的id的值,而不是自增长生成的id的值,对象的属性未赋值,自动初始化的值是0,所以此处主键的值为0,改成BEFORE取的就是对象主键的值。

笔者习惯在写insert语句时将selectKey标签带上,方便使用。

另外:再强调一下,AFTER     BEFORE必须大写

否则,运行如下:

第二种写法详解:

在insert标签中加入useGeneratedKeys和keyProperty属性即可,即:useGeneratedKeys="true" keyProperty="id"

例如:

<insert id="insertSelective" parameterType="com.rkxch.studypaper.po.StoryComments" useGeneratedKeys="true" keyProperty="id">
    insert into story_comments
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="storyId != null">
        story_id,
      </if>
      <if test="userId != null">
        user_id,
      </if>
      <if test="isDisplayName != null">
        is_display_name,
      </if>
      <if test="isSupport != null">
        is_support,
      </if>
      <if test="likeCount != null">
        like_count,
      </if>
      <if test="auditUserId != null">
        audit_user_id,
      </if>
      <if test="auditStatus != null">
        audit_status,
      </if>
      <if test="auditTime != null">
        audit_time,
      </if>
      <if test="dislikeCount != null">
        dislike_count,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="updateTime != null">
        update_time,
      </if>
      <if test="commentsContent != null">
        comments_content,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="storyId != null">
        #{storyId,jdbcType=INTEGER},
      </if>
      <if test="userId != null">
        #{userId,jdbcType=INTEGER},
      </if>
      <if test="isDisplayName != null">
        #{isDisplayName,jdbcType=INTEGER},
      </if>
      <if test="isSupport != null">
        #{isSupport,jdbcType=INTEGER},
      </if>
      <if test="likeCount != null">
        #{likeCount,jdbcType=INTEGER},
      </if>
      <if test="auditUserId != null">
        #{auditUserId,jdbcType=INTEGER},
      </if>
      <if test="auditStatus != null">
        #{auditStatus,jdbcType=INTEGER},
      </if>
      <if test="auditTime != null">
        #{auditTime,jdbcType=TIMESTAMP},
      </if>
      <if test="dislikeCount != null">
        #{dislikeCount,jdbcType=INTEGER},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
      <if test="commentsContent != null">
        #{commentsContent,jdbcType=LONGVARCHAR},
      </if>
    </trim>
  </insert>

效果如下:

 

  • 7
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 MyBatis 循环插入 List 集合到数据库可以使用 MyBatis 的批量插入功能,这样可以大大提高插入效率。具体实现步骤如下: 1. 为 List 集合中的元素创建对应的映射类,例如: ```java public class User { private Integer id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 2. 在 MyBatis 的 mapper.xml 文件中编写批量插入语句,例如: ```xml <insert id="batchInsert" parameterType="java.util.List"> INSERT INTO user (name, age) VALUES <foreach collection="list" item="item" separator=","> (#{item.name}, #{item.age}) </foreach> </insert> ``` 3. 在 Java 代码中调用批量插入语句,例如: ```java // 假设你已经创建了 SqlSessionFactory 对象和 SqlSession 对象 // 假设你要插入的 List 集合为 userList try { sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.batchInsert(userList); sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } ``` 4. 注意事项: - 批量插入语句中的 #{item.xxx} 表示映射类中的属性,例如 #{item.name} 表示 User 类的 name 属性。 - 批量插入语句中使用了 `<foreach>` 标签来循环遍历 List 集合,并将每个元素插入数据库中。 - 在 Java 代码中调用批量插入语句时,需要通过 sqlSession.getMapper() 方法获取对应的 Mapper 接口实例,并调用其中的方法来执行批量插入操作。注意要手动提交事务,否则数据不会写入到数据库中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值