MyBatis 示例-主鍵回填

測試類:com.yjw.demo.PrimaryKeyTest

自增長列

數據庫表的主鍵爲自增長列,在寫業務代碼的時候,經常需要在表中新增一條數據後,能獲得這條數據的主鍵 ID,MyBatis 提供了實現的方法。

StudentMapper.xml

<insert id="insertByAutoInc" parameterType="studentDO" keyProperty="id" 
    useGeneratedKeys="true">
    insert into t_student (name, sex, selfcard_no, note)
    values (
        #{name,jdbcType=VARCHAR},
        #{sex,jdbcType=TINYINT},
        #{selfcardNo,jdbcType=BIGINT},
        #{note,jdbcType=VARCHAR}
    )
</insert>

通過配置兩個屬性(keyProperty、useGeneratedKeys)獲取表中生成的自增長主鍵。

  • keyProperty:表示以哪個列作爲屬性的主鍵,不能和 keyColumn 同時使用,如果你是聯合主鍵可以用逗號將其隔開;
  • useGeneratedKeys:這會令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來取出由數據庫內部生成的主鍵,例如,MySQL 和 SQL Server 自動遞增字段,Oracle 的序列等,但是使用它就必須要給 keyProperty 或者 keyColumn 賦值。useGeneratedKeys 的取值爲布爾值,true/false,默認值爲 false;

批量新增數據,也可以採用和上面一樣的方式。

<insert id="batchInsertByAutoInc" parameterType="list" keyProperty="id" 
        useGeneratedKeys="true">
  insert into t_student (name, sex, selfcard_no, note)
    values 
    <foreach collection="list" item="item" index="index" separator=",">
        (
            #{item.name,jdbcType=VARCHAR},
            #{item.sex,jdbcType=TINYINT},
            #{item.selfcardNo,jdbcType=BIGINT},
            #{item.note,jdbcType=VARCHAR}
        )
    </foreach>
</insert>

非自增長列

假設我們取消表 t_student 的 id 自增的規則,我們的要求是:如果表 t_student 沒有記錄,則我們需要設置 id=1,否則我們就取最大 id 加2,來設置新的主鍵。對於一些特殊的要求,MyBatis 也提供了對應方法。

<insert id="insertByNoAutoInc" parameterType="studentDO">
    <selectKey keyProperty="id" resultType="long" order="BEFORE">
        select if(max(id) is null, 1, max(id) + 2) as newId from t_student
    </selectKey>
    insert into t_student (id, name, sex, selfcard_no, note)
    values (
        #{id,jdbcType=BIGINT},
        #{name,jdbcType=VARCHAR},
        #{sex,jdbcType=TINYINT},
        #{selfcardNo,jdbcType=BIGINT},
        #{note,jdbcType=VARCHAR}
    )
</insert>

批量新增數據,也可以採用和上面一樣的方式。

<insert id="batchInsertByNoAutoInc" parameterType="list">
    <selectKey keyProperty="id" resultType="long" order="BEFORE">
        select if(max(id) is null, 1, max(id) + 2) as newId from t_student
    </selectKey>
    insert into t_student (name, sex, selfcard_no, note)
    values
    <foreach collection="list" item="item" index="index" separator=",">
        (
        #{item.name,jdbcType=VARCHAR},
        #{item.sex,jdbcType=TINYINT},
        #{item.selfcardNo,jdbcType=BIGINT},
        #{item.note,jdbcType=VARCHAR}
        )
    </foreach>
</insert>

 

MyBatis 實用篇

MyBatis 概念

MyBatis 示例-簡介

MyBatis 示例-類型處理器

MyBatis 示例-傳遞多個參數

MyBatis 示例-主鍵回填

MyBatis 示例-動態 SQL

MyBatis 示例-聯合查詢

MyBatis 示例-緩存

MyBatis 示例-插件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章