在mybatis的mapper配置文件中,可以利用<foreach>标签实现sql条件的循环,可完成类似批量的sql
mybatis接受的参数分为:(1)基本类型(2)对象(3)List(4)数组(5)Map
无论传哪种参数给mybatis,他都会将参数放在一个Map中:
如果传入基本类型:变量名作为key,变量值作为value 此时生成的map只有一个元素。
如果传入对象: 对象的属性名作为key,属性值作为value,
如果传入List: "list"作为key,这个List是value (这类参数可以迭代,利用<foreach>标签实现循环)
如果传入数组: "array"作为key,数组作为value(同上)
如果传入Map: 键值不变。
<foreach>标签的用法:
六个参数:
collection:要循环的集合
index:循环索引(不知道啥用。。)
item:集合中的一个元素(item和collection,按foreach循环理解)
open:以什么开始
close:以什么结束
separator:循环内容之间以什么分隔
批量修改方式一:
<update id="pubS" parameterType="Map">
UPDATE BMC_SUBPLATE
SET PLSTATUS = '02'
WHERE
<foreach collection="ids" item="plid" open="" close="" separator="OR">
PLID = #{plid}
</foreach>
</update>
批量修改方式二:
<update id="updateTestcaseNodeBatch" parameterType="List">
<foreach collection="list" item="nodeVO" separator=";">
UPDATE testcase_node
<set>
name=#{nodeVO.name},
version=#{nodeVO.version},
description=#{nodeVO.description},
last_modify_user=#{nodeVO.createUser},
last_modify_time=#{nodeVO.createTime}
</set>
<where>
object_id=#{nodeVO.objectId} AND root_id=#{nodeVO.rootId}
</where>
</foreach>
</update>
方式二可能会报错:
出错信息:
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ';
UPDATE testcase_node
SET name='Türstatus',
version=4,
' at line 8
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near........
解决方法:
仔细检查 map文件 和数据库表字段,确定没有错误
检查 配置的 mysql jdbc 链接字符串 默认不支持一次性执行多个sql 语句;
但是在我们的 update map中需要执行多个 update语句。
最后加上参数 "allowMultiQueries" 设置为true 如下:
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true" />
参照链接:
http://blog.csdn.net/gchonghavefun/article/details/8214223
http://blog.csdn.net/jingshuaizh/article/details/43852513