MyBatisのプライマリ・キーの自己増加-useGeneratedKeys

5724 ワード

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:
 id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username,password,email,bio)
  values (#{username},#{password},#{email},#{bio})

If your database also supports multi-row insert, you can pass a list or an array of Authors and retrieve the auto-generated keys.
 id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username, password, email, bio) values
   item="item" collection="list" separator=",">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  

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):
 id="insertAuthor">
   keyProperty="id" resultType="int" order="BEFORE">
    select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
  
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})