mybatis批量操作
2016-03-10 16:05
323 查看
更新单条记录
?1 | UPDATE course SET name = 'course1' WHERE id = 'id1' ; |
更新多条记录的同一个字段为同一个值
?1 | UPDATE course SET name = 'course1' WHERE id in ( 'id1' , 'id2' , 'id3); |
更新多条记录为多个字段为不同的值
比较普通的写法,是通过循环,依次执行update语句。Mybatis写法如下:
?
1 2 3 4 5 6 7 8 9 | < update id= "updateBatch" parameterType= "java.util.List" > <foreach collection= "list" item= "item" index = "index" open = "" close = "" separator= ";" > update course < set > name =${item. name } </ set > where id = ${item.id} </foreach> </ update > |
一条记录update一次,性能比较差,容易造成阻塞。
MySQL没有提供直接的方法来实现批量更新,但可以使用case when语法来实现这个功能。
?
1 2 3 4 5 6 7 8 9 10 11 12 | UPDATE course SET name = CASE id WHEN 1 THEN 'name1' WHEN 2 THEN 'name2' WHEN 3 THEN 'name3' END , title = CASE id WHEN 1 THEN 'New Title 1' WHEN 2 THEN 'New Title 2' WHEN 3 THEN 'New Title 3' END 更新单条记录?
更新多条记录的同一个字段为同一个值?
更新多条记录为多个字段为不同的值比较普通的写法,是通过循环,依次执行update语句。Mybatis写法如下: ?
一条记录update一次,性能比较差,容易造成阻塞。 MySQL没有提供直接的方法来实现批量更新,但可以使用case when语法来实现这个功能。 ?
这条sql的意思是,如果id为1,则name的值为name1,title的值为New Title1;依此类推。 在Mybatis中的配置则如下: ?
|
这条sql的意思是,如果id为1,则name的值为name1,title的值为New Title1;依此类推。
在Mybatis中的配置则如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | < update id= "updateBatch" parameterType= "list" > update course <trim prefix= "set" suffixOverrides= "," > <trim prefix= "peopleId =case" suffix= "end," > <foreach collection= "list" item= "i" index = "index" > <if test= "i.peopleId!=null" > when id=#{i.id} then #{i.peopleId} </if> </foreach> </trim> <trim prefix= " roadgridid =case" suffix= "end," > <foreach collection= "list" item= "i" index = "index" > <if test= "i.roadgridid!=null" > when id=#{i.id} then #{i.roadgridid} </if> </foreach> </trim> <trim prefix= "type =case" suffix= "end," > <foreach collection= "list" item= "i" index = "index" > <if test= "i.type!=null" > when id=#{i.id} then #{i.type} </if> </foreach> </trim> <trim prefix= "unitsid =case" suffix= "end," > <foreach collection= "list" item= "i" index = "index" > <if test= "i.unitsid!=null" > when id=#{i.id} then #{i.unitsid} </if> </foreach> </trim> </trim> where <foreach collection= "list" separator= "or" item= "i" index = "index" > id=#{i.id} </foreach> </ update > /article/3534051.html |
相关文章推荐
- lucene 调优
- 外国程序员整理的Java资料大全
- getOutputStream() has already been called for this response
- Mybatis的批量更新 bug
- sqlite database browser的使用
- Dubbo实现的源码分析
- java 注解 继承
- 构建高并发高可用的电商平台架构实践 转载
- &lt;div&gt;.&lt;li&gt;上面有好空白大/间距.&lt;/li&gt;.&lt;/div&gt;
- mybatis 批量增加 Parameter '__frch_item_0' not found. Available parameters are [lis
- 详细探究Spark的shuffle实现
- windows下安装redis
- lucene的两种分页操作
- EL(Expression Language)表达式概述
- CSS+DIV固定底部的漂浮导航条(多浏览器兼容)
- 自定义 ForkJoinPool
- Watij——Java开源Web测试工具
- 开源爬虫: Heritrix 3.1 Windows 上安装/使用
- Error was tenMinuteCache Cache: The Disk store is not active.
- Inappropriate OGNL expression