mybatis中foreach使用方法
foreach一共有三种类型,分别为List,[](array),Map三种。
下面表格是我总结的各个属性的用途和注意点。
foreach属性
属性 | 描述 |
---|---|
item | 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。 具体说明:在list和数组中是其中的对象,在map中是value。 该参数为必选。 |
collection | 要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象没有默认的键。 当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子: 如果User有属性List ids。入参是User对象,那么这个collection = "ids" 如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id" 上面只是举例,具体collection等于什么,就看你想对那个元素做循环。 该参数为必选。 |
separator | 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。 |
open | foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。 |
close | foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。 |
index | 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。 |
注:Map类型没有默认的map,所以不能直接写collection="map",如果这么写,需要保证传入的Map参数有@Param("map")注解。
有关参数的更详细内容,建议看:深入了解MyBatis参数
这节讲的是foreach中map的用法。
map和List,array相比,map是用K,V存储的,在foreach中,使用map时,index属性值为map中的Key的值。
因为map中的Key不同于list,array中的索引,所以会有更丰富的用法。
第一个简单例子:
<insert id="ins_string_string">
insert into string_string (key, value) values
<foreach item="item" index="key" collection="map"
open="" separator="," close="">(#{key}, #{item})</foreach>
</insert>
可以看到这个例子相当简单,表中需要两个值,正好和K,V对应,因而map中的一个K,V就对应一条数据,如果map中有多个K,V,就会保存多个结果。
如果map中有两对K,V,那么执行SQL如下:
- DEBUG [main] - ==> Preparing: insert into string_string (key, value) values (?, ?) , (?, ?)
- DEBUG [main] - ==> Parameters: key 1(String), value 1(String), key 2(String), value 2(String)
- DEBUG [main] - <== Updates: 2
大部分数据库是支持values()()这种形式的插入语句,可以插入多条(相关链接 - 可能需翻墙)。
下面再看一个select的例子:
- <select id="sel_key_cols" resultType="int">
- select count(*) from key_cols where
- <foreach item="item" index="key" collection="map"
- open="" separator="AND" close="">${key} = #{item}</foreach>
- </select>
可以看到这里用key=value来作为查询条件,对于动态的查询,这种处理方式可以借鉴。一定要注意到$和#的区别,$的参数直接输出,#的参数会被替换为?,然后传入参数值执行。
上述SQL执行日志如下:
- DEBUG [main] - ==> Preparing: select count(*) from key_cols where col_a = ? AND col_b = ?
- DEBUG [main] - ==> Parameters: 22(Integer), 222(Integer)
- DEBUG [main] - <== Total: 1
最后,如果不考虑元素的顺序和map中Key,map和list,array可以拥有一样的效果,都是存储了多个值,然后循环读取出来。
foreach一共有三种类型,分别为List,[](array),Map三种。
示例一:
<select id="countByUserList" resultType="_int" parameterType="list">
select count(*) from users
<where>
id in
<foreach item="item" collection="list" separator="," open="(" close=")" index="">
#{item.id, jdbcType=NUMERIC}
</foreach>
</where>
</select>
注:select count(*) from users WHERE id in ( ? , ? )
示例二:
<select id="selectStorageProductInventroy" parameterType="java.util.Map" resultType="StorageProductInventroyModel">
select op.inventroy_operation_id ,
op.inventroy_id ,
ty.name as operation_type,
DATE_FORMAT(op.insert_time,'%Y/%m/%d') as insert_time,
em.name as employee,
sm1.name as from_store,
st1.name as to_store,
sm.name as from_storage,
st.name as to_storage,
hi.number,
pr.name as product_name,
pr.category_id as categoryString,
pr.product_code,
hi.amount,
hi.back_amount,
hi.unit,
re.description as operation_reason,
hi.description from inventroy_history hi left join inventroy_operation op
on hi.inventroy_operation_id = op.inventroy_operation_id left join product pr
on hi.product_id =pr.product_id left join operation_type ty
on op.operation_type_id = ty.operation_type_id left join employee em
on op.employee_id = em.employee_id left join (select inventroy_operation.to_storage_id as to_storage_id,storage.name as name
from inventroy_operation , storage
where inventroy_operation.to_storage_id = storage.storage_id) st
on op.to_storage_id = st.to_storage_id left join (select inventroy_operation.from_storage_id as from_storage_id,storage.name as name
from inventroy_operation , storage
where inventroy_operation.from_storage_id = storage.storage_id) sm
on op.from_storage_id = sm.from_storage_id left join (select inventroy_operation.to_store_id as to_store_id,store.name as name
from inventroy_operation , store
where inventroy_operation.to_store_id = store.store_id) st1
on op.to_store_id = st1.to_store_id left join (select inventroy_operation.from_store_id as from_store_id,store.name as name
from inventroy_operation , store
where inventroy_operation.from_store_id = store.store_id) sm1
on op.from_store_id = sm1.from_store_id left join operation_reason re
on hi.operation_reason_id = re.operation_reason_id
WHERE 1=1
<if test="operation_type_id != null and operation_type_id.length != 0">
and
<foreach collection="operation_type_id" item="operationTypeId" index="index" open="(" separator="or" close=")">
op.operation_type_id = #{operationTypeId}
</foreach>
</if>
<if test="storage_id != 0 and storage_id != null">
and (op.from_storage_id = #{storage_id} or op.to_storage_id = #{storage_id})
</if>
<if test="category_id != 0 and category_id != null">
and pr.category_id like concat('%','(',#{category_id},')','%')
</if>
<if test="product_code != null">
and pr.product_code like concat('%',#{product_code},'%')
</if>
<if test="product_name != null">
and pr.name like concat('%',#{product_name},'%')
</if>
and date(op.insert_time) between #{start_time} and #{end_time}
group by hi.inventroy_history_id
</select>
注:and (op.operation_type_id = ? or op.operation_type_id = ?)
示例三:数组
public void testQuery() {
ColInfoDao dao=(ColInfoDao)ctx.getBean("colInfoDao");
Map map = new HashMap();
map.put("userId", "tom");
map.put("password", "123");
String[] a = { "20000001", "20000002" };
map.put("classIds", Arrays.asList(a));
Object password = dao.query(map);
System.out.println("password:" + password);
Assert.assertEquals("123", password);
}
XML:(感觉不适合mybatis,可以使用在ibatis中,iBatis 2.x 和 MyBatis 3.0.x)
<select id="queryPasswordByUserId" parameterClass="java.util.Map" resultClass="java.lang.String">
<![CDATA[
select PASSWORD as password from T_S_P_USER
]]>
<dynamic prepend="where">
<isNotEmpty prepend="AND" property="userId">
USER_ID=#userId#
</isNotEmpty>
<isNotEmpty prepend="AND" property="password">
PASSWORD=#password#
</isNotEmpty>
<isNotEmpty prepend="AND" property="classIds">
<iterate property="classIds" open="(" conjunction="OR" close=")">
CLASS_ID = #classIds[]#
</iterate>
</isNotEmpty>
</dynamic>
</select>
示例四:Map
map和List,array相比,map是用K,V存储的,在foreach中,使用map时,index属性值为map中的Key的值。
因为map中的Key不同于list,array中的索引,所以会有更丰富的用法。
<insert id="ins_string_string">
insert into string_string (key, value) values
<foreach item="item" index="key" collection="map"
open="" separator="," close="">(#{key}, #{item})</foreach>
</insert>
可以看到这个例子相当简单,表中需要两个值,正好和K,V对应,因而map中的一个K,V就对应一条数据,如果map中有多个K,V,就会保存多个结果。
如果map中有两对K,V,那么执行SQL如下:
DEBUG [main] - ==> Preparing: insert into string_string (key, value) values (?, ?) , (?, ?)
DEBUG [main] - ==> Parameters: key 1(String), value 1(String), key 2(String), value 2(String)
DEBUG [main] - <== Updates: 2
下面再看一个select的例子:
<select id="sel_key_cols" resultType="int">
select count(*) from key_cols where
<foreach item="item" index="key" collection="map"
open="" separator="AND" close="">${key} = #{item}</foreach>
</select>
可以看到这里用key=value来作为查询条件,对于动态的查询,这种处理方式可以借鉴。一定要注意到$和#的区别,$的参数直接输出,#的参数会被替换为?,然后传入参数值执行。
DEBUG [main] - ==> Preparing: select count(*) from key_cols where col_a = ? AND col_b = ?
DEBUG [main] - ==> Parameters: 22(Integer), 222(Integer)
DEBUG [main] - <== Total: 1
最后,如果不考虑元素的顺序和map中Key,map和list,array可以拥有一样的效果,都是存储了多个值,然后循环读取出来。
mybatis中foreach使用方法的更多相关文章
- mybatis中foreach的用法(转)
foreach一共有三种类型,分别为List,[](array),Map三种. foreach属性 属性 描述 item 循环体中的具体对象.支持属性的点路径访问,如item.age,item.inf ...
- mybatis中的updateByExampleSelective方法怎么使用
mybatis中的updateByExampleSelective方法怎么使用.sendDetailMapper.updateByExampleSelective(sendDetail, m);参数m ...
- MyBatis中foreach循环的用法
一.在了解foreach之前,先了解一下mybatis传入参数及parameterType 1.我们在Dao层向对应的mapper.xml文件传递参数时,可以传递的参数有: ①.基本数据类型(如int ...
- mybatis中foreach使用
mybatis中的<foreach collection="list" item="item" index="index" open= ...
- 谈一下思考,关于mybatis中<foreach collection="list">中list得来的原因 没看到官方说明
<foreach> 是在sql语句中进行多个id查询 时用到的,因为mybatis代替jdbc和hibernate, 使用 在xml文件中编写sql语句,这是一个标签文件.然后在 dao层 ...
- mybatis 中 foreach 的性能问题及调优
1.mybatis中最初的sql语句 SELECT 参数1, 参数2, 参数3 FROM 表 WHERE 条件参数1 in <foreach item="item" inde ...
- mybatis中foreach参数过多效率很慢的优化
foreach 后面in 传入的参数有1万条,#和$是有效率区别的,$的效率远高于#,上篇文章做了比较. 但没达到我的理想结果. 1. 更改方式,把foreach 去掉,改成拼装方式, 参数直接拼装成 ...
- 用mybatis中的insert方法插入数据,返回值为1,但数据库却没有数据
刚才在写东西的时候,用mybatis中的 <insert id="add" parameterType="cn.entity.Computer"> ...
- mybatis 中 foreach collection的三种用法(转)
文章转自 https://blog.csdn.net/qq_24084925/article/details/53790287 oreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集 ...
随机推荐
- 小菜鸟之SSM框架
# SSM框架 # **什么是框架** 就是模板,将一些基础性的程序和代码由框架模板提供,然后程序员补充和业务需求相关的代码. # **ssm框架组成** s: springMvc 子框架 代替ser ...
- MVCC原理 4步 什么是MVCC、事务ACID、事物隔离级别、Innodb存储引擎是如何实现MVCC的
MVCC是来处理并发的问题,提高并发的访问效率,读不阻塞写.事物A 原子性C 一致性I 隔离性D 持久性高并发的场景下的问题脏读不可重复读幻读事物隔离级别RU读未提交 脏读/不可重复读/幻读 .不适用 ...
- [游戏复刻] 2048(2014. Android)
等哪一天我有很多很多的时间再写吧...
- python+selenium+chrome实现自动登录百度
#python3.4+selenium3.5+chrome版本 63.0.3239.132+chrome驱动chromedriver.exe #实现自动登录百度 from selenium impor ...
- python — 池
1. 池 池分为:进程池.线程池 池:预先的开启固定个数的进程数/线程数,当任务来临的时候,直接提交给已经开好的进程 / 线程,让这个进程 / 线程去执行就可以了. 池节省了进程.线程的开启.关闭.切 ...
- 第十一章 ZYNQ-MIZ701 PS读写PL端BRAM
本篇文章目的是使用Block Memory进行PS和PL的数据交互或者数据共享,通过zynq PS端的Master GP0端口向BRAM写数据,然后再通过PS端的Mater GP1把数据读出来,将 ...
- java中锁的应用
锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchronized(重量级) 和 ReentrantLock(轻量级)等等 ) .这些已经写好提供的锁为我们开发提供了便利. ...
- github骚操作
限制搜索 in关键词限制搜索范围 命令 说明 xxx in:name 项目名包含xxx的 xxx in:description 项目描述包含xxx的 xxx in:readme 项目的readme文件 ...
- spring-boot-plus集成Shiro+JWT权限管理
SpringBoot+Shiro+JWT权限管理 Shiro Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码和会话管理. 使用Shiro的易于理解的API,您可以 ...
- codeforce E - Minimal Labels+hdu 4857
两个题目的意思差不多 都是希望得出的拓扑序如果有多种 要求输出字典序小的情况 这里引用一个大佬的博客 关于为什么不能直接建图然后用小根堆解决这个问题(http://blog.csdn.net/rgno ...