新增一个主键自增长_MyBatis 示例-主键回填
生活随笔
收集整理的這篇文章主要介紹了
新增一个主键自增长_MyBatis 示例-主键回填
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
測試類:com.yjw.demo.PrimaryKeyTest
自增長列
數(shù)據(jù)庫表的主鍵為自增長列,在寫業(yè)務(wù)代碼的時候,經(jīng)常需要在表中新增一條數(shù)據(jù)后,能獲得這條數(shù)據(jù)的主鍵 ID,MyBatis 提供了實現(xiàn)的方法。
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 同時使用,如果你是聯(lián)合主鍵可以用逗號將其隔開;
- useGeneratedKeys:這會令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來取出由數(shù)據(jù)庫內(nèi)部生成的主鍵,例如,MySQL 和 SQL Server 自動遞增字段,Oracle 的序列等,但是使用它就必須要給 keyProperty 或者 keyColumn 賦值。useGeneratedKeys 的取值為布爾值,true/false,默認值為 false;
批量新增數(shù)據(jù),也可以采用和上面一樣的方式。
<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>非自增長列
假設(shè)我們?nèi)∠?t_student 的 id 自增的規(guī)則,我們的要求是:如果表 t_student 沒有記錄,則我們需要設(shè)置 id=1,否則我們就取最大 id 加2,來設(shè)置新的主鍵。對于一些特殊的要求,MyBatis 也提供了對應(yīng)方法。
<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>批量新增數(shù)據(jù),也可以采用和上面一樣的方式。
<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>架構(gòu)筆記 · 語雀?www.yuque.com總結(jié)
以上是生活随笔為你收集整理的新增一个主键自增长_MyBatis 示例-主键回填的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 10 邮件槽_员工主动发离职邮件,提出申
- 下一篇: 喝冬瓜鸡蛋汤可以减肥吗