In Mybatis, after inserting data, several methods to return the latest primary key id, and their specific usage

I. Introduction                                   

  How can database operations be without INSERT operations? Record MyBatis's notes on the INSERT operation below for future reference.

 

2. Detailed explanation of  insert element  attributes                            

  Its properties are as follows:

   parameterType  , the fully qualified class name or type alias of the input parameter

   keyColumn  , set the primary key name automatically generated by the data table. For a specific database (such as PostgreSQL), it must be set if the automatically generated primary key is not the first field

   keyProperty  , the default value of unset, is used to set which property of the domain model the return value of the getGeneratedKeys method or selectKey sub-element will be assigned to

   useGeneratedKeys  , the value range is true|false (default value), sets whether to use the getGenereatedKeys method of JDBC to obtain the primary key and assign it to the domain model property set by keyProperty. MySQL and SQLServer execute auto-generated key fields, so when the database sets the auto-generated primary key, it can be obtained through the getGeneratedKeys method of JDBC. However, databases such as Oralce that do not support auto-generated key fields cannot use this method to obtain the primary key.

   statementType  , the value range is STATEMENT, PREPARED (default value), CALLABLE

   flushCache  , the value range is true (default value)|false, set whether the second-level cache and local cache will be cleared after this operation is performed

   timeout  , the default is unset (depending on the settings of the jdbc driver), set the maximum time limit for performing this operation, the timeout will throw an exception

   databaseId  , the value range oracle|mysql, etc., indicates the database manufacturer, and inside the element, you can specify different sql statements for a specific database through `<if test="_databaseId = 'oracle'">`

 

Third, the general INSERT operation - the return value is the number of records inserted                

mapper interface code:

/**
 * Add student information
 * @param student student instance
 * @return the number of records for successful operations
 */
int add(EStudent student);

mapper.xml:

<insert id="add" parameterType="EStudent">
  insert into TStudent(name, age) values(#{name}, #{age})
</insert

 

4. Obtain the primary key of the record after performing the INSERT operation                        

mapper interface code:

/**
 * Add student information
 * @param student student instance
 * @return the number of records for successful operations
 */
int add(EStudent student);

至于mapper.xml则分为两种情况了,一种是数据库(如MySQL,SQLServer)支持auto-generated key field,另一种是数据库(如Oracle)不支持auto-generated key field的。

 1. 数据库(如MySQL,SQLServer)支持auto-generated key field的情况

    手段①(推荐做法):

<insert id="add" parameterType="EStudent" useGeneratedKeys="true" keyProperty="id">
  insert into TStudent(name, age) values(#{name}, #{age})
</insert>

    手段②:

copy code
<insert id="add" parameterType="EStudent">
  // 下面是SQLServer获取最近一次插入记录的主键值的方式
  <selectKey resultType="_long" keyProperty="id" order="AFTER">
    select @@IDENTITY as id
  </selectKey>
  insert into TStudent(name, age) values(#{name}, #{age})
</insert>
copy code

  由于手段②获取主键的方式依赖数据库本身,因此推荐使用手段①。

 2. 数据库(如Oracle)不支持auto-generated key field的情况

copy code
<insert id="add" parameterType="EStudent">
  <selectKey keyProperty="id" resultType="_long" order="BEFORE">
    select CAST(RANDOM * 100000 as INTEGER) a FROM SYSTEM.SYSDUMMY1
  </selectKey>
  insert into TStudent(id, name, age) values(#{id}, #{name}, #{age})
</insert
copy code

  注意:mapper接口返回值依然是成功插入的记录数,但不同的是主键值已经赋值到领域模型实体的id中了。

 

五、 selectKey子元素 详解                            

  作用:在insert元素和update元素中插入查询语句。

  其属性如下:

     keyProperty ,默认值unset,用于设置getGeneratedKeys方法或selectKey子元素返回值将赋值到领域模型的哪个属性中

     resultType ,keyPropety所指向的属性类全限定类名或类型别名

     order属性 ,取值范围BEFORE|AFTER,指定是在insert语句前还是后执行selectKey操作

     statementType ,取值范围STATEMENT,PREPARED(默认值),CALLABLE

注意:selectKey操作会将操作查询结果赋值到insert元素的parameterType的入参实例下对应的属性中。并提供给insert语句使用

 

六、批量插入                                 

  方式1:

<insert id="add" parameterType="EStudent">
  <foreach collection="list" item="item" index="index" separator=";">
    INSERT INTO TStudent(name,age) VALUES(#{item.name}, #{item.age})
  </foreach>
</insert>

上述方式相当语句逐条INSERT语句执行,将出现如下问题:
1. mapper接口的add方法返回值将是最一条INSERT语句的操作成功的记录数目(就是0或1),而不是所有INSERT语句的操作成功的总记录数目
2. 当其中一条不成功时,不会进行整体回滚。

  方式2(仅限于MSSQL):

copy code
<insert id="add" parameterType="EStudent">
  WITH R AS
  <foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">
    SELECT #{item.name} as a, #{item.age} as b
  </foreach>
  INSERT INTO TStudent(name,age) SELECT a, b FROM R
</insert>
copy code

上述方式解决了方式1中的问题。但该方式仅限于MSSQL

  方式3(通用解决方法)方式3(MSSQL):

 INSERT INTO TStudent(name,age) 
  <foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">
    SELECT #{item.name} as a, #{item.age} as b
  </foreach>

该方式与方式2效果一样,若为Oracle则采用

INSERT INTO TStudent(name,age) 
  <foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">
    SELECT #{item.name} as a, #{item.age} as b FROM DUAL
  </foreach>


Reprinted from: http://blog.csdn.net/sinat_30474567/article/details/51395247

INSERT INTO TStudent(name,age) 
  <foreach collection="list" item="item" index="index" open="(" close=")" separator="union all">
    SELECT #{item.name} as a, #{item.age} as b FROM DUAL
  </foreach>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326007278&siteId=291194637