• Mybatis 在 insert 插入操作后返回主键 id


    前提条件

    假设我们这里有一个 Student 表,结构如下

    其中主键 sid 是自增的,那么我们插入数据时就不用插入 sid,它会生成一个自增的 sid。 

    StudentMapper 接口中的 insert 方法

    int insert(Student student);
    

    StudentMapper.xml 中的 insert 标签

    1. id="insert" parameterType="Student">
    2. insert into student(name, age)
    3. VALUES (#{name} , #{age})

    单元测试类中的方法

    1. @Test
    2. public void insertUser() {
    3. Student student = new Student(0,"xxx", 28);
    4. int n = StudentMapper.insert(student);
    5. }

     

    这里并不能获取到生成的 sid,如果要获取这个 sid,还要根据 name 来查询数据库,而且 name 也需要是 unique 唯一性的。

    那么,有没有办法让我们能够执行插入语句后,直接获取到生成的 sid 呢,当然是有的。

    解决方法

    方法一

    修改 StudentMapper .xml 中的 insert 标签,配置 useGeneratedKeys 和 keyProperty

    1. id="insert" parameterType="Student" useGeneratedKeys="true" keyProperty="sid">
    2. insert into student(name, age)
    3. VALUES (#{name} , #{age})

    说明:

    1、useGeneratedKeys=“true” 设置是否使用JDBC的getGeneratedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中.

    2、keyProperty=“sid” 表示将自增长后的 Id 赋值给实体类中的 sid 字段。

    运行结果:成功返回了主键 sid

    方法二(推荐)

    修改 StudentMapper.xml 中的 insert 标签,在 insert 标签中编写 selectKey 标签

    1. <insert id="insert" parameterType="Student">
    2. insert into student(name, age)
    3. VALUES (#{name} , #{age})
    4. <selectKey keyProperty="sid" order="AFTER" resultType="int">
    5. SELECT LAST_INSERT_ID()
    6. selectKey>
    7. insert>

    说明: 

    1、< insert> 标签中没有 resultType 属性,但是 < selectKey> 标签是有的。
    2、order=“AFTER” 表示先执行插入语句,之后再执行查询语句。
    3、keyProperty=“sid” 表示将自增长后的 Id 赋值给实体类中的 sid 字段。
    4、SELECT LAST_INSERT_ID() 表示 MySQL 语法中查询出刚刚插入的记录自增长 Id。

    运行结果:成功返回了主键 sid

     

     

  • 相关阅读:
    想考【软考高级】,但不具备计算机基础?“系规”适合你
    算法通关村-----原来贪心如此简单
    Python学习路线
    mars3d实现禁止地图移动,禁止地图左右平移,但是鼠标可以移动的效果。
    【面试题】面试官问你前端性能优化时,他想问什么?
    在K8S1.24使用Helm3部署Alluxio2.8.1
    Linux驱动开发(三)---设备树
    删除链表中重复元素的问题
    [13] CUDA_Opencv联合编译过程
    C++——vector
  • 原文地址:https://blog.csdn.net/weixin_42672802/article/details/126381047