mybatis foreach list特殊处理方式

网友投稿 498 2022-08-18


mybatis foreach list特殊处理方式

目录foreach list特殊处理foreach用法 List和Array,对象1、array数组的类型2、list的类型3、对象类型

foreach list特殊处理

最近做一个功能,sql要用到 IN 条件,通过list传入IN 的值,如:

SELECT * FROM table1 WHERE id in (1,2,3)

对应的mybatis写法为:

SELECT * FROM table1

WHERE id

#{rid}

期望结果是按list的值进行查询。

可是,当list为空的时候呢?

sql应该是这样的SELECT * FROM table1 WHERE id in ()。直接在mysql中运行肯定是语法错误的。

无论如何是不会查到数据的,但mybatis又是什么策略呢?直接把这一条where条件给我忽略了…导致查全表数据。

这也不好说mybatis做的好不好,算不算bug了。

既然知道套路了,就得有策略来应对了。于是多写了两个if。

SELECT * FROM table1

WHERE id

#{rid}

= -1

不算是这么上策,但也能解决问题,当list为空时,给id赋值一个-1,保证查不到数据,sql也没有语法错误。

foreach用法 List和Array,对象

向sql传递数组或List,mybatis使用foreach解析

foreach元素的属性主要有item,index,collection,open,separator,close。

item:集合中元素迭代时的别名,该参数为必选。index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。close:foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。

collection:foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的

主要有一下3种情况:

1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

3. 如果使用Map封装了,collection的属性值为对应的Key

1、array数组的类型

UserMapper.java

List findUser_array(int [] ids)throws Exception;

UserMapper.xml

select * from sys_user

#{item}

Controller.java

@RequestMapping("/findUser_array")

@ResponseBody

public List foreach_test()throws Exception{

int [] ids=new int[]{1,2,3};

List list = userMapper.findUser_array(ids);

return list;

}

示例:

2、list的类型

UserMapper.java

List findUser_list(Listlist)throws Exception;

UserMapper.xml

select * from sys_user

#{user_id}

Controller.java

/**

* list类型

* @return

* @throws Exception

*/

@RequestMapping("/findUser_list")

@ResponseBody

public List findUser_list()throws Exception{

List list = userMapper.findUser_list(Arrays.asList(new Integer[]{1,2,3,6}));

return list;

}

测试截图:

3、对象类型

UserMapper.java

List findUser_obj(UserQueryVo vo)throws Exception;

UserMapper.xml

select * from sys_user

#{user_id}

Controller.java

/**

* 对象类型

* @return

* @throws Exception

*/

@RequestMapping("/findUser_obj")

@ResponseBody

public List findUser_obj()throws Exception{

List ids = new ArrayList<>();

ids.add(1);

ids.add(2);

ids.add(3);

UserQueryVo queryVo = new UserQueryVo();

queryVo.setIds(ids);

List list = userMapper.findUser_obj(null);

return list;

}

测试截图:


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java 深入分析链表面试实例题目
下一篇:mybatis foreach 循环 list(map)实例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~