Mybatis自動生成key值(selectKey和useGeneratedKeys)


insert和update操作中會常常用到自動生成主鍵。

 

1.selectKey和useGeneratedKeys屬性 

useGeneratedKeys (insert and update only) This tells MyBatis to use the JDBC getGeneratedKeys method to retrieve keys generated internally by the database (e.g.auto increment fields in RDBMS like MySQL or SQL Server). Default: false (( 僅 對 insert 和update有 用 ) 這 會 告 訴 MyBatis 使 用 JDBC 的 getGeneratedKeys 方法來取出由數據(比如:像 MySQL 和 SQL Server 這樣的數據庫管理系統的自動遞增字段)內部生成的主鍵。默認值:false。)
keyProperty
(insert and update only) Identifies a property into which MyBatis will set the key value returned by getGeneratedKeys , or by a selectKey child element of the insert statement. Default: unset . Can be a comma separated list of property names if multiple generated columns are expected. ((僅對 insert和update有用) 標記一個屬性, MyBatis會通過 getGeneratedKeys 或者通過 insert 語句的 selectKey 子元素設置它的值。默認: 不設置。)
keyColumn
(insert and update only) Sets the name of the column in the table with a generated key. This is only required in certain databases (like PostgreSQL) when the key column is not the first column in the table. Can be a comma separated list of columns names if multiple generated columns are expected.

 

2. selectKey和useGeneratedKeys使用

<insert id="insert">
 <selectKey keyProperty="id" resultType="int" order="BEFORE">
  <if test="_databaseId == 'oracle'">
   select seq_users.nextval from dual
  </if>
  <if test="_databaseId == 'db2'">
   select nextval for seq_users from sysibm.sysdummy1"
  </if>
 </selectKey>
 insert into users values (#{id}, #{name})
</insert>

通過selectKey在插入操作前或者操作后獲取key值,做為字段插入或返回字段。(此段代碼獲取的序列值id作為字段值插入到users表中)

<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
    insert into Author (username,password,email,bio)
    values (#{username},#{password},#{email},#{bio})
</insert>

如果數據庫支持自增長主鍵字段(比如mysql、sql server)設置useGeneratedKeys=”true”和keyProperty,這樣就可以插入主鍵id值 。
oracle則不支持自增長id,設置useGeneratedKey=”false”,如果設置true則會有報錯信息。通過nextval函數,如SEQ_table.Nextval生成id

 

3. 插入更新一條數據時,可以使用selectKey獲取id操作。當做多條數據插入更新時,而selectKey只能使用一次,此時應該使用useGeneratedKeys操作。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM