主要记录Mybatis的增删改使用到的标签属性及意义。参数方面没有过多涉及、后面还是会有单独章节来记录参数的类型及使用。
这里没有查询、因为查询算是比较重要的使用方式、同时也比较复杂、牵涉到ResultMap的配置、关联查询等。分开的目的是想让博客每一篇都有重点、调理清晰一点。
2.2.1对于MySql或者SQL Server这种主键自增长的数据库可以使用如下方式获取主键(其中两个关键标签属性useGeneratedKeys 和keyProperty的意义见上面insert标签属性):
- <insert id="addAuthorWithAutoGeneratedKey" useGeneratedKeys="true" keyProperty="id">
- INSERT INTO author (username, password, email, bio, favourite_section)
- VALUES (#{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
- </insert>
2.2.2对于Oracle这种不支持主键自增长的数据库可以使用下面这种先生成一个主键再插入表并将生成主键返回的方式来笨处理:
- <insert id="addAuthorWithoutAutoGeneratedKey">
- <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>
2.2.3对于Oracle一般主键都会使用Sequence来实现、此时返回新增记录的主键的方式如下:
- <insert id="addAuthor" parameterType="author">
- INSERT INTO author(id, username) VALUES (seq_author.nextval, #{username})
- <selectKey keyProperty="id" resultType="int">
- SELECT max(id) FROM author
- </selectKey>
- </insert>
2.2.4 selectKey:
2.3.1 Mysql中向Author表中插入一条数据并返回主键
- <insert id="addAuthorWithAutoGeneratedKey" useGeneratedKeys="true" keyProperty="id">
- INSERT INTO author (username, password, email, bio, favourite_section)
- VALUES (#{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
- </insert>
2.3.2Oracle中向Author表中插入一条数据并返回主键
- <insert id="addAuthor" parameterType="author">
- INSERT INTO author(id, username) VALUES (seq_author.nextval, #{username})
- <selectKey keyProperty="id" resultType="int">
- SELECT max(id) FROM author
- </selectKey>
- </insert>
将两个放在一起的原因是两者使用的方式比较简单、其中修改使用方式基本和新增差不多。
3.1.1update标签及标签属性
- <update
- id=""
- parameterType="author"
- statementType="PREPARED"
- flushCache="true"
- timeout="20"
- databaseId=""
- keyProperty=""
- keyColumn=""
- useGeneratedKeys="true"/>
3.1.2修改实例
当其未设定主键为返回值时、返回的是数据库中影响的行数。比如修改一条记录、则方法的返回结果为1.
- <update id="updateAuthor" parameterType="author" flushCache="true" statementType="PREPARED">
- UPDATE author
- SET username = #{username}
- WHERE id = #{id}
- </update>
3.2.1delete标签及标签属性
返回的是数据库中影响的行数。比如删除10条记录、则方法的返回结果为10.
- <delete
- id=""
- parameterType="author"
- statementType="PREPARED"
- flushCache="true"
- timeout="20"/>
3.2.2实例
- <delete id="deleteAuthor" parameterType="int">
- DELETE FROM author
- WHERE id = #{id}
- </delete>
github地址:https://github.com/andyChenHuaYing/scattered-items/tree/master/items-mybatis
源码下载地址:http://download.csdn.net/detail/chenghuaying/8713311
联系客服