mybatis中foreach的用法(转)
foreach一共有三种类型,分别为List,[](array),Map三种。
foreach属性
属性 | 描述 |
---|---|
item | 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。 具体说明:在list和数组中是其中的对象,在map中是value。 该参数为必选。 |
collection | 要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象用map代替作为键。 当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array,map将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子: 如果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,该参数可选。 |
示例一:
<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的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合. foreach元素的属性主要有 item,index,collection,open,separator,close. ...
- MyBatis中foreach循环的用法
一.在了解foreach之前,先了解一下mybatis传入参数及parameterType 1.我们在Dao层向对应的mapper.xml文件传递参数时,可以传递的参数有: ①.基本数据类型(如int ...
- Java-MyBatis-杂项: MyBatis 中 in 的用法2
ylbtech-Java-MyBatis-杂项: MyBatis 中 in 的用法2 1.返回顶部 1. 一.简介 在SQL语法中如果我们想使用in的话直接可以像如下一样使用: select * fr ...
- Java-MyBatis:MyBatis 中 in 的用法
ylbtech-Java-MyBatis-杂项:MyBatis 中 in 的用法 1.返回顶部 1. foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合.foreach元 ...
- 【转载】PHP中foreach的用法
http://www.php.cn/php-weizijiaocheng-399438.html 很好用的PHP中foreach的用法详解,收藏!
- AngularJS中forEach的用法
AngularJS中当我们需要遍历某个数组的时候,我们会用到forEach语法.AngularJS中forEach的用法如下: angular.forEach(array,function(obj,i ...
- mybatis中foreach使用方法
作者:学无先后 达者为先 作者:偶尔记一下 foreach一共有三种类型,分别为List,[](array),Map三种. 下面表格是我总结的各个属性的用途和注意点. foreach属性 属性 描述 ...
- 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层 ...
随机推荐
- SAP 透明表之间的关联字段
VTTK-TPLST=TTDST-TPLST(装运点的关联表及描述表字段TTDST-BEZEI) VTTK-ROUTE=TVROT-ROUTE(装运线路关联表及描述表字段TVROT-BEZEI) VT ...
- pgpool介绍和安装经验
Pgpool的介绍 一.介绍 是一个工作在PostgreSQL多服务器和PostgreSQL数据库客户端之间的中间件. 二.概念图 三.功能 连接池:pgpool -Ⅱ保存 连 接到PostgreSQ ...
- Effective C++ -----条款20:宁以pass-by-reference-to-const替换pass-by-value Prefer pass-by-reference-to-const to pass-by-value
尽量以pass-by-reference-to-const替换pass-by-value.前者通常比较高校,并可避免切割问题(slicing problem). 以上规则并不适用于内置类型,以及STL ...
- 大数计算_BigNum优化_加减乘除乘方取余_带注释_数组
#include <iostream> #include <algorithm> #include <cstring> #include <cstdlib&g ...
- Navicat 回复 psc 文件 Mysql
在mysql 中回复 psc文件 的时候 只能一步步来,先在navicat中建一个空数据库,然后点击有上角的备份==>回复备份==> 找到psc文件==> 注意此时不要急于点击 开始 ...
- ajaxFileUpload上传文件没反应
调用jquery的ajaxFileUpload异步上传文件,IE浏览器不进入success问题 原因:json转换异常,ie浏览器处理后的返回json没有<pre>标签,直接是完整的jso ...
- iOS开发中调试小技巧
对于软件开发而言,调试是必须学会的技能,重要性不言而喻.对于调试的技能,基本上是可以迁移的,也就是说你以前在其他平台上掌握的很多调试技巧,很多也是可以用在iOS开发中.不同语言.不同IDE.不同平台的 ...
- VS2010 自动跳过代码现象
今日,发现在Release的调试模式下,VS2010会“莫名其妙”的跳过一些代码不执行. 经实验,初步判断可能的原因:预处理器指令或编译器/连接器优化. 20150703更新: 部分代码: m_pTa ...
- 【JAVA集合框架之List与Set】
一.概述 JAVA的集合框架中定义了一系列的类,这些类都是存储数据的容器.与数组.StringBuffer(StringBuilder)相比,它的特点是: 1.用于存储对象. 2.集合长度可变. 3. ...
- 【JAVA多线程概述】
一.多线程概述 一个进程中至少有一个线程,每一个线程都有自己运行的内容,这个内容可以称为线程要执行的任务. 不能没一个问题都使用多线程,能使用单线程解决的问题就不要使用多线程解决. 使用多线程的弊端: ...