Mybatis中的in查询和foreach标签
Mybatis中的foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
foreach元素的属性主要有 item,index,collection,open,separator,close:
item:表示集合中每一个元素进行迭代时的别;
index:指定一个名字,用于表示在迭代过程中,每次迭代到的位置;
open:表示该语句以什么开始;
separator:表示在每次进行迭代之间以什么符号作为分隔 符;
close:表示以什么结束;
collection:
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在breast里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key
下面分别来看看上述三种情况的示例代码:
<1>单参数List的类型:
<select id="dynamicForeachTest" resultType="Blog">
select * from t_blog where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
上述collection的值为list,对应的Mapper是这样的:
public List<Blog> dynamicForeachTest(List<Integer> ids);
测试代码:
@Test
public void dynamicForeachTest() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
ids.add(6);
List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
for (Blog blog : blogs){
System.out.println(blog);
}
session.close();
}
<2>单参数Array的类型:
<select id="dynamicForeach2Test" resultType="Blog">
select * from t_blog where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
上述collection为array,对应的Mapper代码:
public List<Blog> dynamicForeach2Test(int[] ids);
对应的测试代码:
@Test
public void dynamicForeach2Test() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
int[] ids = new int[] {1,3,6,9};
List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
for (Blog blog : blogs){
System.out.println(blog);
}
session.close();
}
<3>多参数封装成Map的类型:
<select id="dynamicForeach3Test" resultType="Blog">
select * from t_blog where title like "%"#{title}"%" and id in
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
对应测试代码:
@Test
public void dynamicForeach3Test() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
final List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(6);
Map<String, Object> params = new HashMap<String, Object>();
params.put("ids", ids);
params.put("title", "中国");
List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
for (Blog blog : blogs)
System.out.println(blog);
session.close();
}
<4>嵌套foreach的使用:
map 数据如下 Map<String,List<Long>>
测试代码如下:
public void getByMap(){
Map<String,List<Long>> params=new HashMap<String, List<Long>>();
List<Long> orgList=new ArrayList<Long>();
orgList.add(10000003840076L);
orgList.add(10000003840080L); List<Long> roleList=new ArrayList<Long>();
roleList.add(10000000050086L);
roleList.add(10000012180016L); params.put("org", orgList);
params.put("role", roleList); List<BpmDefUser> list= bpmDefUserDao.getByMap(params);
System.out.println(list.size());
}
dao代码如下:
public List<BpmDefUser> getByMap(Map<String,List<Long>> map){
Map<String,Object> params=new HashMap<String, Object>();
params.put("relationMap", map);
return this.getBySqlKey("getByMap", params);
}
xml代码如下:
<select id="getByMap" resultMap="BpmDefUser">
<foreach collection="relationMap" index="key" item="ent" separator="union">
SELECT *
FROM BPM_DEF_USER
where RIGHT_TYPE=#{key}
and OWNER_ID in
<foreach collection="ent" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</foreach>
</select>
index 作为map 的key。item为map的值,这里使用了嵌套循环,嵌套循环使用ent。
《项目实践》
@Override
public Container<Map<String,Object>> findAuditListInPage(
Map<String, Object> params) {
//1、参数组装
PageModel pageMode = new PageModel();
try {
if(params.get("page")!=null){
pageMode.setPage(Integer.parseInt(params.get("page").toString()));
}
if(params.get("rows")!=null){
pageMode.setRows(Integer.parseInt(params.get("rows").toString()));
}
} catch (Exception e) {
Assert.customException(RestApiError.COMMON_ARGUMENT_NOTVALID);
}
//分页条件组装
pageMode.putParam(params);
if(params.get("startCreateTime") !=null){
Date parse = DateUtil.parse(params.get("startCreateTime").toString(), DateUtil.yyyyMMddHHmmss);
params.put("startCreateTime",parse);
}
if(params.get("endCreateTime") !=null){
Date parse = DateUtil.parse(params.get("endCreateTime").toString(), DateUtil.yyyyMMddHHmmss);
params.put("endCreateTime",parse);
}
if(params.get("type") !=null){ //type可以多选
String typeString = params.get("type").toString();
String typeArray [] = typeString.split(",");
params.put("type", typeArray);
}
if(params.get("state") !=null){ //state可以多选
String stateString = params.get("state").toString();
if(stateString.equals(DictConstants.APPLICATION_STATE.AUDITING)
||stateString.equals(DictConstants.APPLICATION_STATE.WAITING_AUDIT)){
stateString = "waitingAudit,auditing";
}
String stateArray [] = stateString.split(",");
params.put("state", stateArray);
}
//分页数据组装
Container<Map<String,Object>> container = new Container<Map<String,Object>>();
List<Map<String,Object>> auditModelList = cmApplicationRepo.findAuditList(params);
for(Map<String,Object> audit:auditModelList){
//设置是否关注过
Long auditId = Long.parseLong(audit.get("auditId").toString());
Long auditPersonId = Long.parseLong(params.get("auditPersonId").toString());
Map<String, Object> followMap = new HashMap<String,Object>();
followMap.put("sourceType", DictConstants.FOLLOW_SOURCE_TYPE.FOLLOW_APPLICATION);
followMap.put("sourceId", auditId);
followMap.put("userId", auditPersonId);
List<BizFollowModel> followList = bizFollowService.find(followMap);
if(followList!= null && followList.size()>0){
audit.put("isFollow", "true");
}else{
audit.put("isFollow", "false");
}
}
container.setList(auditModelList);
container.setTotalNum(cmApplicationRepo.countAuditListNumber(params));
return container;
}
DAO
@Override
public List<Map<String,Object>> findAuditList(Map<String, Object> map) {
return findList("getAuditList", map);
}
xml
<!-- 查询申请列表-->
<select id="getApplicationList" resultType="java.util.Map" parameterType="map">
select
a.ID AS id,
a.STATE AS stateCode, b.DICT_VALUE AS stateValue,
a.ITEM AS itemCode, c.DICT_VALUE AS itemValue,
a.TYPE AS typeCode, d.DICT_VALUE AS typeValue,
a.APP_PERSON_ID AS appPersonId,
a.CREATE_TIME AS createTime
from cm_application a
LEFT JOIN cm_dict_type b on a.STATE = b.DICT_CODE AND b.TYPE = 'Application_State'
LEFT JOIN cm_dict_type c on a.ITEM = c.DICT_CODE
LEFT JOIN cm_dict_type d on a.TYPE = d.DICT_CODE
where 1=1
<if test="item != null" >
and a.ITEM = #{item,jdbcType=VARCHAR}
</if>
<if test="type != null" >
and a.TYPE IN
<foreach item="typeArray" index="index" collection="type" open="(" separator="," close=")">
#{typeArray}
</foreach>
</if>
<if test="appPersonId != null" >
and a.APP_PERSON_ID = #{appPersonId,jdbcType=BIGINT}
</if>
<if test="state != null" >
and a.STATE IN
<foreach item="stateArray" index="index" collection="state" open="(" separator="," close=")">
#{stateArray}
</foreach>
</if>
<!-- 分页查询时,要选择createTime在starCreateTime和endCreatetTime之间的记录 -->
<if test="startCreateTime != null" >
and a.CREATE_TIME >= #{startCreateTime,jdbcType=TIMESTAMP}
</if>
<if test="endCreateTime != null" >
and a.CREATE_TIME <= #{endCreateTime,jdbcType=TIMESTAMP}
</if>
order by a.ID
<include refid="Paging" />
</select>
Mybatis中的in查询和foreach标签的更多相关文章
- mybatis中的高级查询
Mybatis作为一个ORM框架,肯定是支持sql高级查询的. 下面的一个案例来为大家详细讲解mybatis中的高级查询. 案例说明: 此案例的业务关系是用户,订单,订单详情与商品之间的关系. 以订单 ...
- 【mybatis】mybatis中放置IN查询拼接sql过长,IN查询进行分批次查询的处理
需要使用的切割list集合的工具类,链接:https://www.cnblogs.com/sxdcgaq8080/p/9376947.html 处理逻辑,原本的一个LIst,进行切割,循环进行myba ...
- SSM-MyBatis-13:Mybatis中多条件查询
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 实体类 public class Book { private Integer bookID; private ...
- Mybatis中使用级联查询,一对多的查询
一.需求描述 自己在开发一个小程序的过程中,需要做的一个查询是稍微比较复杂的查询,根据用户信息去查询用户所对应的宠物信息. 一个用户可能对应多个宠物,所以在用户和宠物信息的对应关系就是一对多的关系. ...
- Mybatis中的模糊查询
今天下午做的一个功能,要用到模糊查询,字段是description,刚开始我的写法用的是sql中的模糊查询语句, 但是这个有问题,只有将字段的全部值传入其中,才能查询,所以不是迷糊查询. 后来经过搜索 ...
- mybatis 根据多个id查询数据 foreach标签
//根据设备多个id获取设备信息 public List<Devices> getDevicesAll(@Param("devicesIds") String[] de ...
- java使用插件pagehelper在mybatis中实现分页查询
摘要: com.github.pagehelper.PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件 PageHelper是国内牛人的一个开源项目,有兴趣的可以去看源码,都有 ...
- mybatis中sql语句查询操作
动态sql where if where可以自动处理第一个and. <!-- 根据id查询用户信息 --> <!-- public User findUserById(int id) ...
- mybatis sql in 查询(mybatis sql语句传入参数是list)mybatis中使用in查询时in怎么接收值
1.in查询条件是list时 <select id="getMultiMomentsCommentsCounts" resultType="int"> ...
随机推荐
- C#程序
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...
- [c#]获取exchange中的图片
摘要 在exchange 2007或者2010中获取的邮件内容为html标签格式,也就是一个页面.如果里面含有img标签,你会发现img标签的src属性为cid:xxxxxxxxxxxx的一串字符串, ...
- ASP.NET Web API与Owin OAuth:调用与用户相关的Web API(非第三方登录)
授权完成添加属性 ClaimsIdentity oAuthIdentity = await CreateAsync(user/*userManager*/, OAuthDefaults.Authent ...
- seo与sem的关系和区别
seo与sem仅有一个字母之差,而且两者和网站优化都有很大的关系,很多初学者往往会把这2个名称弄混,即使一些做了多年的seo,有时候也无法区分这两者之间到底有何不同. 首先,我们从定义上来区分:SEO ...
- 类调用类的protected或private的成员函数或成员变量
1.在其中一个类定义友元函数,则可以实现该类直接使用另外类的里所有内容. 一般实例化两个类,友元类以及自身类,实现友元类传递指针到自身类 2.如果两个类是可以继承的关系,则在子类里继承该类,实现在子类 ...
- phpcms二次开发学习
1.新建模块就是phpcms/modules/目录下面新建文件夹,文件夹名即为模块名. 2.模块内 一般新建三个文件夹:classes(模块要使用的类放置在这个文件夹,通过pc_base::load_ ...
- JS清除IE浏览器缓存的方法
js中自动清除ie缓存方法 — 常用 对于动态文件,比如 index.asp?id=... 或者 index.aspx?id=... 相信有经验的程序员都知道怎样禁止浏览器缓存数据了.但是对于静态文件 ...
- 新技能get——斜率优化
好久没写博客了……我终于回来了…… dp总是令我很头疼的问题之一,然而我还是要学一下怎么优化它. 下面请看一道题吧: [bzoj3675][Apio2014]序列分割 试题描述 小H最近迷上了一个分割 ...
- 字符串驱动技术—— MethodAddress , MethodName , ObjectInvoke
首先看一段Delphi帮助中的介绍(After Delphi 6 ): Returns the address of a published method. class function Method ...
- CI控制器中设置在其它方法中可用的变量
开发过程中,某些变量可能需要被控制器中的其它方法所调用,这个变量改怎么设置呢? 其实可以用ci的$this->load->vars($array);和$this->load-> ...