Java中如何传一个数组作为筛选条件操作数据库(sql中foreach的使用)。

版权声明:如有转载请注明出处 https://blog.csdn.net/hdp134793/article/details/82906770

实现步骤(以多个id作为入参为例):
1.在前端先传一个str,以逗号作为分隔符,将该str传递给后端接口;
2.在后端pojo里面先定义一个list作为存放变量相关po定义如下:
private List ids;//id的集合
3.然后针对传入的str进行解析,以split进行截取,将截取的值塞到定义的ids
4.Java方法实现如下java代码段:
5.针对数据,在mapper.xml进行sql的处理,通过sql的foreach方法进行处理
6.具体前后端实现代码如下(包括sql)
前端js:

var str = '12,34,26,79,55';
	  $.ajax({
		  //这个地方接口路径根据自己的情况来写
		  url:xx/xx/resertAlertid,
		  type:'POST',
          dataType:'json',
          async:false,
          data:{
        	"str":str
          },
          success : function(data) {
          }
	  })

Java代码段

@ResponseBody
	@RequestMapping(value="/resertAlertid")
	public int resertAlertid(alertmodelPo ipo,HttpServletRequest request,String str){
		int res =0;
		List<Integer> idarr = new ArrayList<Integer>();
		String[] getstr = str.split(",");
		for(int i=0;i<getstr.length;i++){
			idarr.add(Integer.parseInt(getstr[i]));
		}
		ipo.setIds(idarr);
		res = service.resertAlertid(ipo);
		return res;
	}

Sql执行代码mapper.xml(mybatis)

<update id="resertAlertid" parameterType="alertindexPo">
		 <if test="po.ids != null and po.ids != ''">
		 	 update alert_profile_dict
	   	 		set 
	   	 	 use_flag = 'f'
			 where 1=1
			and id in 
			<foreach collection="po.ids" open="(" close=")" item="item" separator=",">
	            #{item}
	        </foreach>
		 </if>
	</update>

只要以上代码,基本所有有关集合条件查询的都能解决,针对不同类型的就只要改变对应的po类型和解析类型就可以,希望大家有个好心情今天。

猜你喜欢

转载自blog.csdn.net/hdp134793/article/details/82906770
今日推荐