2025-04-25
๋์ SQL(Dynamic SQL)์ ์กฐ๊ฑด์ ๋ฐ๋ผ SQL๋ฌธ์ด ์ ๋์ ์ผ๋ก ์์ฑ๋๋ ๊ธฐ๋ฅ์ ๋๋ค.
๋ณต์กํ ๊ฒ์ ์กฐ๊ฑด, ์ ํ์ ํํฐ๋ง์ด ํ์ํ ๊ฒฝ์ฐ์ ํ์์ ์ผ๋ก ์ฌ์ฉ๋ฉ๋๋ค.
๐ก ์์ ์ํฉ
- ๊ฒ์์ฐฝ์์ ์ ๋ ฅํ ๊ฐ์ ๋ฐ๋ผ WHERE ์กฐ๊ฑด์ด ๋ฌ๋ผ์ง ๋
- ํน์ ํ๋ผ๋ฏธํฐ๊ฐ ์์ ๋๋ง ์ฟผ๋ฆฌ ์กฐ๊ฑด ์ถ๊ฐ
ํ๊ทธ | ์ค๋ช |
---|---|
<if> | ์กฐ๊ฑด์ ๋ฐ๋ผ SQL ์ผ๋ถ๋ฅผ ํฌํจ |
<choose> | ์๋ฐ์ switch-case์ ์ ์ฌ |
<when> | <choose> ๋ด๋ถ ์กฐ๊ฑด ๋ถ๊ธฐ |
<otherwise> | ๋ชจ๋ <when> ์กฐ๊ฑด์ด false์ผ ๋ ์คํ |
<where> | ์๋์ผ๋ก WHERE ์ ์ถ๊ฐ, ๋ถํ์ํ AND/OR ์ ๊ฑฐ |
<trim> | SQL ์๋ค๋ก ํน์ ๋ฌธ์์ด ์ถ๊ฐ/์ ๊ฑฐ |
<if>
ํ๊ทธ ํ์ฉ<select id="Select_if_xml" parameterType="java.util.Map" resultType="java.util.Map">
SELECT * FROM tbl_memo
<if test="type != null and type.equals('text')">
WHERE text LIKE CONCAT('%', #{keyword}, '%')
</if>
</select>
@Test
void testSelectIfXml() {
Map<String,Object> param = new HashMap<>();
param.put("type", "text");
param.put("keyword", "a");
List<Map<String,Object>> response = memoMapper.Select_if_xml(param);
response.forEach(System.out::println);
}
{id=3002, text=aaaaa, writer=example@example.com, createAt=2025-04-25T15:38}
โก ํฌ์ธํธ:
ํ๋ผ๋ฏธํฐ
type
์ด "text"์ผ ๋๋ง WHERE ์กฐ๊ฑด์ด ์ถ๊ฐ๋ฉ๋๋ค.
<choose>
๋ก ์กฐ๊ฑด ๋ถ๊ธฐ<select id="Select_when_xml" parameterType="java.util.Map" resultType="java.util.Map">
SELECT * FROM tbl_memo
<if test="type != null">
WHERE
<choose>
<when test="type.equals('id')">
id LIKE CONCAT('%', #{keyword}, '%')
</when>
<when test="type.equals('writer')">
writer LIKE CONCAT('%', #{keyword}, '%')
</when>
<otherwise>
createAt <= #{keyword}
</otherwise>
</choose>
</if>
</select>
@Test
void testSelectWhenXml() {
Map<String,Object> param = new HashMap<>();
param.put("type", "writer");
param.put("keyword", "example");
List<Map<String,Object>> response = memoMapper.Select_when_xml(param);
response.forEach(System.out::println);
}
{id=3001, text=asd, writer=example@example.com, createAt=2025-04-25T15:38}
{id=3002, text=aaaaa, writer=example@example.com, createAt=2025-04-25T15:38}
{id=3003, text=bbbb, writer=example@example.com, createAt=2025-04-25T15:38}
๐ก ํฌ์ธํธ:
type
๊ฐ์ ๋ฐ๋ผ ๊ฒ์ ์ปฌ๋ผ์ด ์ ๋์ ์ผ๋ก ๋ณ๊ฒฝ๋ฉ๋๋ค.์กฐ๊ฑด์ด ์์ผ๋ฉด
<otherwise>
๊ฐ ์คํ๋ฉ๋๋ค.
<where>
ํ๊ทธ ์ ๊ทน ํ์ฉtest="param != null"
)<if>
๋จ๋ฐ ๊ธ์ง โก๏ธ ๊ฐ๋
์ฑ ์ ํ<trim>
์ผ๋ก ์ ๋ฆฌ<if>
์ <choose>
๋ฅผ ์ ์ ํ ์กฐํฉํ๋ฉด ๊น๋ํ ์ฟผ๋ฆฌ ์์ฑ ๊ฐ๋ฅ์ง์ ํ ์คํธ ์ฝ๋๋ฅผ ์์ฑํ๋ฉฐ ๋์ SQL์ ๋์ ๋ฐฉ์์ ํ์คํ ์ดํดํ ์ ์์์ต๋๋ค.
๋ณต์กํ ์กฐ๊ฑด์ผ์๋ก XML ๋งคํผ์ ํ์์ฑ์ ๋ค์ ํ๋ฒ ๋๊ผ๊ณ , ์ค๋ฌด์์ ์ด๋ป๊ฒ ํ์ฉํ ์ง ๊ฐ์ด ์กํ์ต๋๋ค! ๐