首先,mysql须要数据库链接配置&allowMultiQueries=truejava
jdbc:mysql://127.0.0.1:3306/mybank?useUnicode=true&characterEncoding=utf8&allowMultiQueries=truemysql
oracle下支持执行多条语句,下面3个相同sql
<update id="batchUpdate" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";" > update T_EMP_1 <set> age = #{item.age}+1,name=#{item.name} </set> where id = #{item.id} </foreach> </update>
<update id="batchUpdate" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="begin" close="end;" separator="" > update T_EMP_1 <set> age = #{item.age}+1,name=#{item.name} </set> where id = #{item.id}; </foreach> </update>
<update id="batchUpdate" parameterType="java.util.List"> begin <foreach collection="list" item="item" index="index" separator="" > update T_EMP_1 <set> age = #{item.age}+1,name=#{item.name} </set> where id = #{item.id}; </foreach> end; </update>
foreach的主要用在构建in条件中,它能够在SQL语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。item表示集合中每个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程当中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号做为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,可是在不一样状况 下,该属性的值是不同的,主要有一下3种状况:
1. 若是传入的是单参数且参数类型是一个List的时候,collection属性值为list
2. 若是传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3. 若是传入的参数是多个的时候,咱们就须要把它们封装成一个Map了,固然单参数也能够封装成map,实际上若是你在传入参数的时候,在breast里面也是会把它封装成一个Map的,map的key就是参数名,因此这个时候collection属性值就是传入的List或array对象在本身封装的map里面的key 数据库
批量删除数组
<delete id="batchDeleteStudent" parameterType="List"> DELETE FROM STUDENT WHERE id IN <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </delete>
批量更新 注意:oracle中 形如 update *** set *** where ** in(....) 这种语句 in所在的集合有条数限制 为1000条oracle
<update id="batchUpdateStudent" parameterType="List"> UPDATE STUDENT SET name = "5566" WHERE id IN <foreach collection="list" item="item" index="index" open="(" separator="," close=")" > #{item} </foreach> </update>
<update id="batchUpdateStudentWithMap" parameterType="Map" > UPDATE STUDENT SET name = #{name} WHERE id IN <foreach collection="idList" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </update>
批量插入 mysql和oracle不同spa
mysql: <insert id="batchInsertStudent" parameterType="java.util.List"> INSERT INTO STUDENT (id,name,sex,tel,address) VALUES <foreach collection="list" item="item" index="index" separator="," > (#{item.id},#{item.name},#{item.sex},#{item.tel},#{item.address}) </foreach> </insert>
oracle: <insert id="insertBatch4Oracle" parameterType="List"> insert into aa(a,b) <foreach collection="list" item="item" index="index" separator="union all" > select #{item.a},#{item.b} from dual </foreach> </insert>