-
增删改实例语句
- <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中主键设置auto_increment,主流的数据库一般都支持,当然也有其他不支持的。。。
-
分类
-
数据库支持自动生成主键
-
方法
- 可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置到目标属性上就OK了
-
实例
- <insert id="insertAuthor" useGeneratedKeys="true"
keyProperty="id">
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
- <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>
-
数据库不支持自动生成主键
-
方法
- 在insert中使用selectKey语句
- <selectKey keyProperty="id" resultType="int" order="BEFORE" statementType="PREPARED">
-
愚蠢例子
- <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>
- 随机生成一个 ID做为主键
- 在上面的示例中,selectKey 元素将会首先运行,Author 的 id 会被设置,然后插入语句会被调用。这给你了一个和数据库中来处理自动生成的主键类似的行为,避免了使 Java 代码变得复杂