Mjybatis之update,delete,insert

来源:互联网 发布:wamp mysql 密码 编辑:程序博客网 时间:2024/04/17 05:49

insert,update和delete

数据变更语句 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">

下面就是 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>
如前所述,插入语句的配置规则更加丰富,在插入语句里面有一些额外的属性和子元素用来处理主键的生成,而且有多种生成方式。
首先,如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置到目标属性上就OK了。例如,如果上面的 Author 表已经对 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.
<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>
对于不支持自动生成类型的数据库或可能不支持自动生成主键 JDBC 驱动来说,MyBatis 有另外一种方法来生成主键。 
这里有一个简单(甚至很傻)的示例,它可以生成一个随机 ID(你最好不要这么做,但这里展示了 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>
在上面的示例中,selectKey 元素将会首先运行,Author 的 id 会被设置,然后插入语句会被调用。这给你了一个和数据库中来处理自动生成的主键类似的行为,避免了使 Java 代码变得复杂。 
selectKey 元素描述如下:
<selectKey  keyProperty="id"  resultType="int"  order="BEFORE"  statementType="PREPARED">



0 0
原创粉丝点击