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:

 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})


你可能感兴趣的:(mybatis)