MyBatis foreach¸¦ ÀÌ¿ëÇÑ ¹è¿ ÆĶó¹ÌÅÍ »ðÀÔÇϱâ
Äõ¸®¸¦ ÀÛ¼ºÇØ¾ß ÇÒ¶§ Àü´Þ¹ÞÀº ÀÎÀÚ°ªÀ» ¹ÙÅÁÀ¸·Î ¹Ýº¹ÀûÀÎ SQL ±¸¹®À» ÀÛ¼ºÇÒ¶§ À¯¿ëÇÏ´Ù.
´ëÇ¥ÀûÀ¸·Î üũ¹Ú½ºµî°ú °°Àº ÀÎÀÚ°ªÀÌ µ¿ÀÏÇÑ ´Ù¼öÀÇ ¹è¿ µ¥ÀÌÅ͸¦ °Ë»öÁ¶°Ç¿¡ ¹Ý¿µÇØ¾ß ÇÒ¶§°¡ Àִµ¥, À̶§ OR ±¸¹® ¶Ç´Â IN ±¸¹®À¸·Î ÀÛ¼ºÇϸé Æí¸®ÇÏ°Ô »ç¿ëÇÒ ¼ö ÀÖ´Ù.
´Ù¸¸ foreachÀÇ °æ¿ì ÀÎÀÚ°ªÀ¸·Î List¿Í Array ÇüÅÂÀÇ collection ŸÀÔ¸¸ »ç¿ëÀÌ °¡´ÉÇÏ´Ù.
foreach ±âº» ¹®¹ý ÇüÅÂ
<foreach collection="sUser_type" item="type" open="(" close=")" separator="or"> |
collection = Àü´Þ¹ÞÀº ÀÎÀÚ. List³ª Array ÇüŸ¸ °¡´É
item = Àü´Þ¹ÞÀº ÀÎÀÚ°ªÀ» alias ¸íÀ¸·Î ´ëü
open = ÇØ´ç ±¸¹®ÀÌ ½ÃÀ۵ɶ§ »ðÀÔÇÒ ¹®ÀÚ¿
close = ÇØ´ç ±¸¹®ÀÌ Á¾·áµÉ¶§ »ðÀÔÇÒ ¹®ÀÚ¿
separator = ¹Ýº¹ µÇ´Â »çÀÌ¿¡ Ãâ·ÂÇÒ ¹®ÀÚ¿
index=¹Ýº¹µÇ´Â ±¸¹® ¹øÈ£ÀÌ´Ù. 0ºÎÅÍ ¼øÂ÷ÀûÀ¸·Î Áõ°¡
List ÇüŸ¦ ³Ñ°åÀ» °æ¿ìÀÇ ¿¹Á¦.
<
java
Code>
List sUserTP = new ArrayList();
sUserTP.add("SP");
sUserTP.add("BX");
HashMap hm = new HashMap();
hm.put("sUser_age", 23) ;
hm.put("sUser_type", sUserTP) ;
<
SQL
Mapper>
<
select
id
=
"getTList"
resultType
=
"hashmap"
parameterType
=
"hashmap"
>
SELECT
name, age
FROM
TB_user
WHERE
age = #{sUser_age} AND
<
foreach
collection
=
"sUser_type"
item
=
"type"
open
=
"("
close
=
")"
separator
=
"or"
>
user_type = #{type.value}
</
foreach
>
</
select
>
¶Ç´Â or ±¸¹®À» IN ±¸¹®À¸·Î º¯°æ
<
select
id
=
"getTList"
resultType
=
"hashmap"
parameterType
=
"hashmap"
>
SELECT
name, age
FROM
TB_user
WHERE
age = #{sUser_age} AND
user_type IN
<
foreach
collection
=
"sUser_type"
item
=
"type"
open
=
"("
close
=
")"
separator
=
","
>
#{type.value}
</
foreach
>
</
select
>
Array ÇüŸ¦ ³Ñ°åÀ» °æ¿ìÀÇ ¿¹Á¦.
<
java
Code>
String[] sUserTP = {"SP", "BX"} ;
HashMap hm = new HashMap();
hm.put("sUser_age", 23) ;
hm.put("sUser_type", sUserTP) ;
<
SQL
Mapper>
<
select
id
=
"getTList"
resultType
=
"hashmap"
parameterType
=
"hashmap"
>
SELECT
name, age
FROM
TB_user
WHERE
age = #{sUser_age} AND
user_type IN
<
foreach
collection
=
"sUser_type"
item
=
"type"
index
=
"index"
open
=
"("
close
=
")"
separator
=
","
>
#{type[index]}
</
foreach
>
</
select
>
foreach¸¦ Àß ÀÌ¿ëÇÏ¸é ´Ü¼ø °Ë»ö»Ó¸¸ ¾Æ´Ï¶ó µ¿ÀÏÇÑ ±¸¹®À¸·Î ÀÌ·ç¾îÁø ´Ù¼öÀÇ INSERT, UPDATEµµ ÀÛ¼ºÀÌ °¡´ÉÇÏ´Ï ¿©·¯ ¹æ¸éÀ¸·Î »ç¿ëÀÌ °¡´ÉÇÏ´Ù.
Ãâó: http://fruitdev.tistory.com/187 [°úÀÏ°¡°Ô °³¹ßÀÚ]