引言
数据库的不同,决定了批量更新语句的差别!
批量 Update
- Mysql
<update id="updateSomething" parameterType="java.util.List">
update userTable
<foreach collection="list" item="user" index="index">
<if test="user.status !=null and user.status != -1">
when id=#{user.id} then #{user.status}
</if>
<if test="user.status == null or user.status == -1">
when id=#{user.id}
</if>
</foreach>
where id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
- Oracle
参数类型:List\<User> users
<update id="updateSomething" parameterTye="com.alibaba.User">
<foreach collection="list" item="user" open="begin" searator=";" close=";end;">
update userTable set id = #{user.id}
where
<choose>
<when test = "user.age == null or user.age == ''">
name = #{user.name}
</when>
<otherwise>
name = #{user.name} and age = #{user.age}
</otherwise>
</foreach>
</update>
注意:获取参数时都要带上user变量,如#{user.xxx}
批量 Insert
- Mysql
如果你的数据库还支持多行插入, 你也可以传入一个 Author 数组或集合,并返回自动生成的主键。
<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 处理问题的灵活性及其所关心的广度):
- Oracle
<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>
批量 Select
- Mysql
- Oracle
参数类型:List\<User> users
<select id="selectSomething" resultType="hashmap">
select * from
where id in
<foreach collection="users" item="user" open="(" searator="," close=")">
#{user.id}
</foreach>
</select>