MySQL如何自动获取主键(MyBatis执行Insert操作返回自增主键)

你好我是辰兮,很高兴你能来阅读。本篇整理了项目实战遇到的问题,解决如何获取数据库中自增的主键问题。


一、项目案例

比如现在一个学生Student表 有三个字段 id(主键自增) name age;

你增加一个学生,你只是添加了name 和 age 但是你想获取新增学生的主键。应该如何获取呢?

/**
 * 添加学生信息
 * @param student 学生实例
 * @return 成功操作的记录数目
 */
int add(Student student);

正常Mybatis操作

<insert id="add" parameterType="Student">
  insert into Student(name, age) values(#{name}, #{age})
</insert

执行Insert(插入)操作后获取记录主键

解决方法一

<insert id="add" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
  insert into Student(name, age) values(#{name}, #{age})
</insert>

解决方法二

<insert id="add" parameterType="Student">
  // 下面是SQLServer获取最近一次插入记录的主键值的方式
  <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER">
     SELECT LAST_INSERT_ID() AS id
  </selectKey>
  insert into Student(name, age) values(#{name}, #{age})
</insert>

由于方法二获取主键的方式依赖数据库本身,因此推荐使用方法一。


keyProperty ,默认值unset,用于设置getGeneratedKeys方法或selectKey子元素返回值将赋值到领域模型的哪个属性中。

useGeneratedKeys ,取值范围true|false(默认值),设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。


二、实战分享

分享一下我项目实战中遇到的相关问题:只展示postman的测试部分。

场景:像CSDN博客评论一样,评论完后还要返回评论。

在这里插入图片描述

问题是:评论表的评论id是自动增长的,你传的时候不用传评论id,点赞数,用户头像,用户姓名等等,但是你返回的时候这些东西都是要有的,所以你要自己封装进去。


正常Mybatis操作:postman的测试传评论

我们可以发现传入的什么返回的就是什么 如id为null
在这里插入图片描述

在Mybatis中进行配置:postman的测试传评论
在这里插入图片描述
我们发现我们可以获取到评论的id,这个评论id是数据库自增的,但是通过配置可以自动装配并返回过来。


Hope that we can grow and progress as soon as possible and become an excellent Java Development Engineer.

猜你喜欢

转载自blog.csdn.net/weixin_45393094/article/details/106790013
今日推荐