사실 요번 편은 foreach문이 주인공이 아니다.

where절에 foreach문을 쓰고 싶은데 넘어온 파라미터가 배열이 아닐 때 배열형으로 만들어 주는 함수를 구현해본다.

 

[html]

<form name="frm" method="post">

<input type="checkbox" name="p_codes" value="01">신축

<input type="checkbox" name="p_codes" value="02">보수

<input type="checkbox" name="p_codes" value="03">증축

</form>

이 세 개의 체크박스를 모두 체크하고 submit을 했다고 치자.

 

code값이 01이거나 02이거나 03인것을 갖고 오는 쿼리문을 작성한다고 할 때 웬지 foreach문이 쓰고 싶다면 

아래함수를 만들어 배열로 구현해준다.

[Utils.java]

1
2
3
4
5
6
7
8
9
10
11
12
13
public static  List <String> makeForeach (String s, String gb){
    List<String> list =   new ArrayList<String>();
    String[] aCode = s.split(gb);
 
    if (s == null || "".equals(s)) {
        return null;
    }
    for(int i=0; i< aCode.length; i++){
        list.add(aCode[i].toString());
    }
 
    return list;
}
cs

 

이제 파라미터를 받아서 배열로 변경해보자. logger로 찍어보면 배열로 찍힐 것이다.

1
List<String> list p_codes = Utils.makeForeach(Utils.nullToStr(parms.get("p_codes")), ","); //여기서 콤마는 구분자임. 다른 구분자로도 사용가능
cs

 

 

그리고 마무리로 foreach를 사용한 쿼리문

[query.xml]

1
2
3
4
5
6
<if test='p_codes !=null'> 
AND CODE IN
<foreach collection="p_codes" item="code" index="index" separator="," open="(" close=")">
        #{code}
</foreach>
</if>
cs

+ Recent posts