美文网首页
Mybatis 文档篇 3.2:Mapper XML 之 ins

Mybatis 文档篇 3.2:Mapper XML 之 ins

作者: 兆雪儿 | 来源:发表于2019-03-23 13:24 被阅读0次

    1 Mapper XML

    2 insert, update and delete

    2.1 insert, update 和 delete 的属性

    The data modification statements insert, update and delete are very similar in their implementation:
    数据变更语句 insert、update 和 delete 是很相似的:

    <insert
      id="insertAuthor"
      parameterType="domain.blog.Author"
      flushCache="true"
      statementType="PREPARED"
      keyProperty=""
      keyColumn=""
      useGeneratedKeys=""
      timeout="20">
    
    <update
      id="updateAuthor"
      parameterType="domain.blog.Author"
      flushCache="true"
      statementType="PREPARED"
      timeout="20">
    
    <delete
      id="deleteAuthor"
      parameterType="domain.blog.Author"
      flushCache="true"
      statementType="PREPARED"
      timeout="20">
    
    • id
      A unique identifier in this namespace that can be used to reference this statement.
      该命名空间可以被用来引用该语句的的唯一标识。

    • parameterType
      The fully qualified class name or alias for the parameter that will be passed into this statement. This attribute is optional because MyBatis can calculate the TypeHandler to use out of the actual parameter passed to the statement. Default is unset.
      传入这条语句的参数的完全限定类名或别名。这个属性是可选的,因为MyBatis 可以自己推断出传入这条语句的实参对应的 TypeHandler。默认未设置。

    • parameterMap
      This is a deprecated approach to referencing an external parameterMap. Use inline parameter mappings and the parameterType attribute.
      已废弃,用来指向外部的 parameterMap。使用行内参数映射和 parameterType 属性。

    • flushCache
      Setting this to true will cause the 2nd level and local caches to be flushed whenever this statement is called. Default: true for insert, update and delete statements.
      设置该属性为 true 会使二级缓存和本地缓存被清空,无论何时该语句被调用。默认:true。

    • timeout
      This sets the maximum number of seconds the driver will wait for the database to return from a request, before throwing an exception. Default is unset (driver dependent).
      这个设置是在抛出异常之前,驱动等待数据库返回请求结果的秒数。默认未设置(依赖驱动)。

    • statementType
      Any one of STATEMENT, PREPARED or CALLABLE. This causes MyBatis to use Statement, PreparedStatement or CallableStatement respectively. Default: PREPARED.
      值为 STATEMENT, PREPARED 或 CALLABLE 其中的一个,这个设置使 MyBatis 使用 Statement, PreparedStatement 或 CallableStatement。默认:PREPARED。

    • 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.
      (仅针对 insert 和 update)通过生成的键值设置表中的列名。这个设置仅在某些数据库(如 PostgreSQL ),当主键的列不是表中的第一列的时候是必须设置的。如果期望得到多个生成的列,可以是使用逗号分隔的属性名称列表。

    • databaseId
      In case there is a configured databaseIdProvider, MyBatis will load all statements with no databaseId attribute or with a databaseId that matches the current one. If case the same statement if found with and without the databaseId the latter will be discarded.
      如果配置了一个 databaseIDProvider,MyBatis 将会加载所有不带 databaseId 或者匹配当前数据库的 databaseId 的语句。如果带或者不带databaseId 的相同语句都有,那么不带的会被忽略。

    insert, update 和 delete 语句的例子:

    <insert id="insertAuthor">
      insert into Author (id,username,password,email,bio)
      values (#{id},#{username},#{password},#{email},#{bio})
    </insert>
    
    <update id="updateAuthor">
      update Author set
        username = #{username},
        password = #{password},
        email = #{email},
        bio = #{bio}
      where id = #{id}
    </update>
    
    <delete id="deleteAuthor">
      delete from Author where id = #{id}
    </delete>
    

    2.2 insert 额外的属性和子元素

    As mentioned, insert is a little bit more rich in that it has a few extra attributes and sub-elements that allow it to deal with key generation in a number of ways.
    如上所述,insert 语句的配置规则更加丰富,它里面有几个额外的属性和子元素可以使它有几种方式来处理主键生成。

    2.2.1 useGeneratedKeys

    First, if your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set useGeneratedKeys="true" and set the keyProperty to the target property and you're done. For example, if the Author table above had used an auto-generated column type for the id, the statement would be modified as follows:
    首先,如果你的数据库支持主键自动生成(如 MySQL 和 SQL Server),你可以简单地设置 useGeneratedKeys="true",然后再把 keyProperty 设置到目标属性上就可以了。例如,如果上面的 Anthor 表使用了一个主键自动生成的列 id,那么语句可以修改为下面这样:

    <insert id="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.
    如果你的数据库也支持多行插入,你可以传入一个 list 或者一个 Anthor 数组,并且返回自动生成的主键。

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

    2.2.2 selectKey

    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.
    对于不支持自动生成主键的数据库或者目前不支持自动生成主键的 JDBC 驱动,MyBatis 还有另外一个方式来处理数据库的主键生成。

    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 的简单(甚至很傻)的例子(你最好不要这么做,这里仅是为了展示 MyBatis 的灵活度和 MyBatis 关心的范围)。

    <insert id="insertAuthor">
      <selectKey keyProperty="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>
    

    In the example above, the selectKey statement would be run first, the Author id property would be set, and then the insert statement would be called. This gives you a similar behavior to an auto-generated key in your database without complicating your Java code.
    在上面的例子中,selectKey 语句会被先运行,Author 的 id 属性会被设置,之后 insert 语句才会被调用。这提供给你一个不使 Java 代码变复杂的同时与数据库自动生成主键功能类似的方式。

    selectKey 的属性:

    <selectKey
      keyProperty="id"
      resultType="int"
      order="BEFORE"
      statementType="PREPARED">
    
    • keyProperty
      The target property where the result of the selectKey statement should be set. Can be a comma separated list of property names if multiple generated columns are expected.
      selectKey 语句要设置的目标属性。如果期望得到多个生成的列,可以是使用逗号分隔的属性名称列表。

    • keyColumn
      The column name(s) in the returned result set that match the properties. Can be a comma separated list of column names if multiple generated columns are expected.
      匹配属性的返回结果集中的列名。如果期望得到多个生成的列,可以是使用逗号分隔的列名列表。

    • resultType
      The type of the result. MyBatis can usually figure this out, but it doesn't hurt to add it to be sure. MyBatis allows any simple type to be used as the key, including Strings. If you are expecting multiple generated columns, then you can use an Object that contains the expected properties, or a Map.
      返回结果的类型。MyBatis 通常可以推算出来,但为了更加明确写上也没什么问题。MyBatis 允许任何简单类型作为主键类型,包含字符串。如果你期望作用于多个生成的列,那么你可以使用包含所有期望属性的一个 Object 或一个 Map。

    • order
      This can be set to BEFORE or AFTER. If set to BEFORE, then it will select the key first, set the keyProperty and then execute the insert statement. If set to AFTER, it runs the insert statement and then the selectKeystatement – which is common with databases like Oracle that may have embedded sequence calls inside of insert statements.
      该属性值可设置为 BEFORE 或者 AFTER 。如果设置为 BEFORE ,它会首先选择主键,设置 keyProperty ,然后执行插入语句;如果设置为 AFTER ,它会首先运行插入语句,然后才运行 selectKey 语句——这和 Oracle 很像,在插入语句内部可能会有嵌入索引调用。

    • statementType
      Same as above, MyBatis supports STATEMENT, PREPARED and CALLABLE statement types that map to Statement, PreparedStatement and CallableStatement respectively.
      同上,MyBatis 支持 STATEMENT, PREPARED 和 CALLABLE 语句类型,分别对应于 Statement, PreparedStatement 和 CallableStatement 。

    最后

    说明:MyBatis 官网提供了简体中文的翻译,但个人觉得较为生硬,甚至有些地方逻辑不通,于是自己一个个重新敲着翻译的(都不知道哪里来的自信...),有些地方同官网翻译有出入,有些倔强地保留了自己的,有的实在别扭则保留了官网的,这些都会在实践中一一更正。鉴于个人英文能力有限,文章中保留了官方文档原英文介绍(个别地方加以调整修剪),希望有缘看到这里的朋友们能够有自己的理解,不会被我可能错误或不合理的翻译带跑偏(〃'▽'〃),欢迎指正!

    当前版本:mybatis-3.5.0
    官网文档:MyBatis
    官网翻译:MyBatis 简体中文
    项目实践:MyBatis Learn

    相关文章

      网友评论

          本文标题:Mybatis 文档篇 3.2:Mapper XML 之 ins

          本文链接:https://www.haomeiwen.com/subject/dzirvqtx.html