๋กœ์ผ“๐Ÿพ
article thumbnail

foreach ๊ตฌ๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด SQL๋ฌธ์—์„œ ํ•œ๋ฒˆ์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

<foreach> ํƒœ๊ทธ์˜ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์†์„ฑ

 

์†์„ฑ ์„ค๋ช…
collection array์™€ list ์ธ์Šคํ„ด์Šค๋ฅผ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. list ์‹œ์—๋Š” list๋กœ ํ‘œ์‹œํ•˜๊ณ  array ์‹œ์—๋Š” array๋กœ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค.
index foreach๋ฌธ์ด ๋ฐ˜๋ณต๋ ๋•Œ๋งˆ๋‹ค 1์”ฉ ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ ์ ‘๊ทผํ•˜๋Š” ๊ฐ’์˜ ์œ„์น˜๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.
item collection์˜ ์†์„ฑ์— ์ง€์ •๋œ ๊ฐ’์— ์ ‘๊ทผํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰, ์†์„ฑ ์ด๋ฆ„์ด๋ผ๊ณ  ๋ณด์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
open ํ•ด๋‹น ๊ตฌ๋ฌธ์ด ์‹œ์ž‘๋  ๋•Œ์˜ ์ง€์ •ํ•œ ๊ธฐํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
close ํ•ด๋‹น ๊ตฌ๋ฌธ์ด ๋๋‚  ๋•Œ์˜ ์ง€์ •ํ•œ ๊ธฐํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
separator ๋ฐ˜๋ณต๋˜๋Š” ์ฟผ๋ฆฌ๋ฌธ ์‚ฌ์ด์— ์ง€์ •ํ•œ ๊ธฐํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.

 


l <foreach> ์˜ˆ์‹œ

 

<select id="selectForEach" parameterType="memberVO" resultType="memberVO">
	SELECT
		*
	FROM TEST_TABLE
	WHERE 1=1
		AND NAME IN
		<foreach item="item" collection="list" open="(" close=")" separator=",">
			#{item}
		</foreach>
</select>

 

์˜ˆ์‹œ๋ฅผ ํ†ตํ•ด <foreach> ํƒœ๊ทธ์˜ ์†์„ฑ๋“ค์„ ๋ณด์‹œ๋ฉด ์ข€ ๋” ์ดํ•ด๊ฐ€ ๋น ๋ฅผ ๊ฒ๋‹ˆ๋‹ค.

 

public MemberVO selectForEach() {
	sqlMapper = getInstance();
	SqlSession session = sqlMapper.openSession();
	MemberVO memberVO = new MemberVO();
	List<String> nameList = new ArrayList<String>();
	
	nameList.add("๊น€๋ณ‘์ค€");
	nameList.add("ํ™์ง€์›");
	
	List<String> resultList = session.selectList("mapper.member.selectForEach", nameList);
	
	
	return memberVO;
}

 

nameList์— ์œ„์™€ ๊ฐ™์€ ์†์„ฑ์„ ์ถ”๊ฐ€ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.

 

SELECT * FROM TEST_TABLE WHERE 1=1 AND name in ('๊น€๋ณ‘์ค€','ํ™์ง€์›');

 

<foreach>๋ฅผ ์ด์šฉํ•œ ์ฟผ๋ฆฌ๋ฌธ์€ ์œ„ ์ฝ”๋“œ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

์ถœ๋ ฅ ๊ฒฐ๊ณผ

 

 

์ฝ์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

์งˆ๋ฌธ์€ ์–ธ์ œ๋‚˜ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค.

 

"๋‚œ ๋ฐ˜๋“œ์‹œ ๋ฐฑ์—”๋“œ ์™•์ด ๋ ๊ฑฐ์•ผ"

profile on loading

Loading...