insert 、update 和 delete
<insert id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" keyProperty="" keyColumn="" useGeneratedKeys="" timeout="20">
<update id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20">
<delete id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20"> | ||||||||||||||||||||||
| ||||||||||||||||||||||
属性 | ||||||||||||||||||||||
| ||||||||||||||||||||||
| ||||||||||||||||||||||
示例 | ||||||||||||||||||||||
<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> | ||||||||||||||||||||||
| ||||||||||||||||||||||
自动生成主键 | ||||||||||||||||||||||
如果数据库支持自动生成主键,可以设置 useGeneratedKeys= "true", 而且设置 keyProperty 到已经做好的目标属性上。例如,如果上面的 Author 表已经对 id 使用了自动生成的列类型,那么语句可以修改为: | ||||||||||||||||||||||
<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id"> insert into Author (username,password,email,bio) values (#{username},#{password},#{email},#{bio}) </insert> | ||||||||||||||||||||||
MyBatis 有另外一种方法来处理数据库不支持自动生成类型,或者可能 JDBC 驱动不支 持自动生成主键时的主键生成问题。 | ||||||||||||||||||||||
<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"> | ||||||||||||||||||||||
|