美文网首页
MyBatis 常见主键返回策略

MyBatis 常见主键返回策略

作者: 青丶空 | 来源:发表于2020-08-07 11:41 被阅读0次

支持主键自增的数据库

<isnert> 标签中增加 useGenerateKeyskeyProperty 属性。

<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:

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

相关文章

网友评论

      本文标题:MyBatis 常见主键返回策略

      本文链接:https://www.haomeiwen.com/subject/lnzirktx.html