1. 程式人生 > >MyBatis之主鍵自增——useGeneratedKeys

MyBatis之主鍵自增——useGeneratedKeys

如果你的資料庫支援主鍵自增,例如MySQL和SQL Server,那麼你可以簡單的設定 useGeneratedKeys="true" ,用keyProperty 去指定主鍵名稱, if the Authortable above had used an auto-generated column type for the id, the statement would be modified as follows:

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

If your database also supports multi-row insert, you can pass a list or an array of Authors and retrieve the auto-generated keys.

<insertid="insertAuthor"useGeneratedKeys="true"keyProperty="id">
  insert into Author (username, password, email, bio) values
  <foreachitem="item"
collection="list"separator=","> (#{item.username}, #{item.password}, #{item.email}, #{item.bio}) </foreach></insert>

MyBatis has another way to deal with key generation for databases that don't support auto-generated column types, or perhaps don't yet support the JDBC driver support for auto-generated keys.

Here's a simple (silly) example that would generate a random ID (something you'd likely never do, but this demonstrates the flexibility and how MyBatis really doesn't mind):

<insertid="insertAuthor"><selectKeykeyProperty="id"resultType="int"order="BEFORE">
    select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
  </selectKey>
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>