如何将一个list传入到mySql语句进行查询

本文介绍两种使用MySql进行批量查询的方法。一是将list封装成Map传入,通过<foreach>标签实现动态SQL,适用于复杂的数据处理场景;二是直接传递list和参数,简化调用过程,提高代码可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何将一个list传入到mySql语句进行查询

方法(一)
将list封装成一个Map传入进去

	//(1)将如下字符串分隔之后放入到list里面
	String cols = ”1,2,3,4,5,6”;
	List<String> yids = new ArrayList<String>();
	String[] as = cols.split(",");
	for(String s : as){
		yids.add(s);
	}
	//(2)将list放到Map里面,正常的传入到后台
	Map<String, Object> map2 = new HashMap<String, Object>();
	Long productId = 1111;
	map2.put("ids", yids);
	map2.put("productId", productId);
	specDataMapper.updateInvalidByProductIdAndCols1(map2);

mapper中sql语句如下

<update id="updateInvalidByProductIdAndCols1">
	    update tbl_mall_spec_data
	    set invalid = 1
	    where product_id = #{productId,jdbcType=BIGINT}
	     and cols1 not in 
	     //注意connection里面是ids item里面就是传过来的集合
	    <foreach collection="ids" item="item" index="index" open="(" separator="," close=")">
		   #{item}
	    </foreach>
  </update>

方法(二)
(1)将如下字符串分隔之后放入到list里面

    Long productId = 1111;
	String cols = ”1,2,3,4,5,6”;
	List<String> yids = new ArrayList<String>();
	String[] as = cols.split(",");
	for(String s : as){
		yids.add(s);
	}
	specDataMapper.updateInvalidByProductIdAndCols1(yids,productId);
	

(2)service注意 由于传进去的是两个参数 所以需要加上@Param 否者不会识别此参数

List<SysModel> getModelListByIds(@Param List<String> ids,@Param Long productId);

(3)mapper中sql语句如下

<update id="updateInvalidByProductIdAndCols1">
	    update tbl_mall_spec_data
	    set invalid = 1
	    where product_id = #{productId,jdbcType=BIGINT}
	     and cols1 not in 
	     //注意由于直接传入的是list所以connection里面是list   item里面就是传过来的集合
	    <foreach collection="list" item="item" index="index" open="(" separator="," close=")">
  			#{item}
  	    </foreach>
  </update>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值