mybatis插入记录时如何获取当前插入记录的自增长的id、主键

时间:2025-04-16 09:11:34

在学习开发过程中,往往会对数据进行一系列操作,

今天就学习一下如何在mybatis 中insert 一条记录返回插入记录的id 也就是主键。

平时我们插入一张表的数据的时候 id都会设成主键且自增长,而这个id有时我们会将与其它表中的字段进行联系所以会需要插入的时候就获取到id值。

设计表主键,自增主键,一般为int类型

我们使用<selectKey>标签获取

    <selectKey resultType="" order="AFTER" keyProperty="id">
        select last_insert_id()
    </selectKey>

order属性:MySQL数据库中,需要设置为after;Oracle需要设置为before

keyProperty:对应对象中需要被赋值的属性,所谓主键

举个例子:

controller:

long number = (student);

studentService: 

public long saveStudent(Student student) {
        long number =  (student);
        return  number;
}

 studentMapper:

int insert(Student student);

xml:  在insert语句的头上直接加入就好。

<insert >

    <selectKey resultType="" order="AFTER" keyProperty="id">
        select last_insert_id()
    </selectKey>
    insert into student (姓名,班级) values (#{name, jdbcType=VARCHAR},
     #{class, jdbcType=VARCHAR},)
</insert>

当完成插入后 学生实体会多了一个id属性记录插入的id; 直接()就可以获取

controller:        (());//  执行前为null

                        long number = (student);

                        (());//输出插入记录的id(执行后)

                        (number);//number 为1  代表操作成功