Mybatis foreach 个人总结

1、传递进来为list集合

<select id="queryList04" resultType="map" parameterType="java.util.List">
          select CEZJRC_TXLJ,CEZJRC_XM,CEZJRC_ZY,CEZJRC_ZC from NRJRENCAI 
          where CEZJRC_BM in 
          <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
            #{item}  
        </foreach>
  </select>

其中<foreach>这个标签是用来循环传入的集合的,collection="list"这个参数中有list,map两种,还有就是自定义的参数,item="item"这个参数可以自定义,用来循环集合里面的值,这个参数的取名要和下面#()这个里面的取名一致。

parameterType="java.util.List"这个传入的参数类型必须这么写,不能简写成List,参数的返回类型也需要明确。
下面是Dao层的调用示例

public List<Map> queryList04(List list);

这样就可以实现传入一个list集合作为参数。

 

2、传递参数为字符串(分隔符分隔)

1. String ids = "1,2,3,4,5,6",如ids作为参数传递,查询list返回。mybatis用foreach处理并返回。 

 
        SELECT *
            FROM yp_popup_store_info store
           
            WHERE 1=1 
	        <if test="formId != null and formId != ''">
                    and store.store_id in
            <foreach item="item" index="index" collection="ids.split(',')"  open="(" separator="," close=")">
                '${item}'
            </foreach>
            </if>

2.注意: (1)ids不能为null,否则报空指针异常。(2)因为字符串内的值是数值类型,所以 用单引号 将元素扩起来,而且使用$,而不用#

3、传递参数为map

方式一:

mybatis更新sql语句:

<update id="publishT00_notice" parameterType="Map">
update test  
set createdate = #{createdate},
creator = #{creator}
where id in 
<foreach collection="ids" item="ids" separator="," open="(" close=")">
#{ids}
</foreach>
</update>

传入map参数类型:

HashMap<String,Object> map = new HashMap<String, Object>();
map.put("creator", "creator");
map.put("createdate", "createdate");

String[] ids = {"1","2"};
map.put("ids", ids );

方式二:

第一步在你的mapper写上:

 List<WeixinUserLocationList> findweixinUserLocations(@Param("params") Map<String, Object> map);

注意就是注解@param 这个,是mybatis的

然后在xml中这样写:

<if test="params.accountId!=null">
            and a.accountid=#{params.accountId}
        </if>
        <if test="params.nickname!=null and params.nickname !=''">
            and a.nickname like '%${params.nickname}%'
        </if>
        <if test="params.beginDate!=null and params.beginDate!=''">
            and date_format(a.createtime,'%Y-%m-%d')>=${params.beginDate}
        </if>
        <if test="params.endDate!=null and params.endDate!=''">
        <![CDATA[    and date_format(a.createtime,'%Y-%m-%d')<=${params.endDate}  ]]>     
        </if>

${params.nickname}这种写法参数默认是传字符串,
#{params.accountId}可以取Long,Integer之类的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值