MyBatis 常见主键返回策略

it2025-10-20  8

支持主键自增的数据库

在 <isnert> 标签中增加 useGenerateKeys 和 keyProperty 属性。

<insert id="saveUser" useGeneratedKeys="true" keyProperty="id"> INSERT INTO user(username,password,email) VALUES (#{username},#{password},#{email}) </insert>

当使用注解时

@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")

不支持主键自增的数据库

在 <insert> 标签内部增加 <selectKey> 标签

<insert id="saveUser" parameterType="com.study.domain.User"> <!-- 配置保存时获取插入的id --> <selectKey keyColumn="id" keyProperty="id" resultType="int"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO user(username,password,email) VALUES (#{username},#{password},#{email}) </insert>

当使用 MyBatis 批量插入时返回主键

<!-- 批量新增 --> <insert id="saveUser" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id" > INSERT INTO user(username,password,email) VALUES <foreach collection="list" index="index" item="users" separator=","> (#{username},#{password},#{email}) </foreach> </insert>

ps:

MyBatis 最低版本至少为 3.3.1。官方在这个版本中加入了批量插入返回的功能。在 Dao 层不能使用 @param 注解。 Mapper.xml 中使用 parameterType="java.util.List" 接收 Dao 中的参数集合。
最新回复(0)