在ibatis 使用 in 语句进行查询的几种方案

来源:互联网 发布:嫁给程序员好吗 编辑:程序博客网 时间:2024/06/07 10:32
在ibatis 使用 in 语句进行查询的几种方案


在进行数据库查询的时候我们难免会遇到需要查询的过滤条件是在几个特定的ID中进行查询,这时就用到了in语句查询,不过在用Java使用in进行查询,有几点需要注意。


1、当Java代码传入参数是数组时
string[] arrays = new string[] { "1", "2", "3" }; --这种方式我是很少见。Reader.QueryForList<?>("Ibatisnet.dao.TestArray, arrays );<select id="TestArray"  resultClass="dto">   select *   from UserInfo   where userId in   <iterate open="(" close=")" conjunction="," >   #[]#   </iterate>   </select>   


2、使用上面的数组还可以使用对象中数组方式
<select id="TestArray"  resultClass="dto">   select *   from UserInfo   where userId in   <iterate open="(" close=")" conjunction="," property="ArrValue" >    #ArrValue[]#   </iterate>   </select>   


3、 in 后面的数据是String(231,3344)传入 ,但是记住如果是:请使用$ $,而不是# #,不过通过转化依然可以使用# #。
使用$,但这种写法存在一定的风险,可能会引起sql注入。
当时使用# #区数据的时候在进行查询的时候过滤条件会变成‘231,3344’这种形式,所以得不到的数据。

<select id="queryAllUserinfo" parameterClass="dto"  resultClass="dto">  SELECT u.USERID,ui.id,  u.USERNAME,u.ACCOUNT,ui.address,ui.idnumber,ui.modify_tm  from eauser u,TB_USER_INFO ui   WHERE u.ACCOUNT = ui.ACCOUNT  <dynamic>   <isNotEmpty prepend="AND" property="userids">   ui.id in ($userids$)  </isNotEmpty>  </dynamic>  </select> 


4、使用 foreach标签(在第3条中,我们在Java代码中把的(231,3344)转化成list或者Array数组再使用下面方式进行查询),另外还可以在数据库里面拆分字符串。
<foreach  item="item" collection="listTag" index="index"  open="(" separator="," close=")">
#{item}
</foreach>


foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名.
index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置.
open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.
close表示以什么结束.


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

<select id="addList" resultType="map">select * from tp_trade where  id in <foreach  item="item" collection="list" index="index"  open="(" separator="," close=")">#{item}</foreach></select>传入参数的代码为:List<Object>  addList(List<Object> ids);

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

<select id="addArray" resultType="map">select * from tp_trade where  tt_type in <foreach  item="item" collection="array" index="index"  open="(" separator="," close=")">#{item}</foreach></select>传入的参数代码为:List<Object> addArray(String[]  ids);


3.如果多个参数,我们会封装成map类型,然后在把需要遍历的list或者array封装到map中。
传入的参数代码为:String str = "1,2,3,4";//转化Map  map = new HashMap();map.put("type",str.spit(","));再把封装好map传入到方法中。List<Object> addMap(Map<String,Object> map);<select id="addMap" resultType="map">select * from tp_trade where  type in <foreach  item="item" collection="type" index="index"  open="(" separator="," close=")">#{item}</foreach></select>


type就是数组集合,使用item遍历即可。





每天努力一点,每天都在进步。