[Mybatis] 매퍼의 동적 SQL 조합(Include, Where, Set) 예제
MyBatis에서는 동적 SQL을 조합하는 데 사용되는 여러 요소가 있습니다. 가장 일반적으로 사용되는 것은 <include>
, <where>
, <set>
등입니다. 이러한 요소를 사용하여 동적 SQL을 조합할 수 있습니다. 아래는 각각의 요소를 사용하는 예제입니다.
예제: 매퍼에서 동적 SQL 조합
- **
요소를 사용한 동적 SQL 조합**:
<!-- UserMapper.xml -->
<mapper namespace="com.example.UserMapper">
<select id="getUserWithFilters" resultType="User">
SELECT * FROM users
WHERE
<include refid="userFilters" />
</select>
<sql id="userFilters">
<!-- 필터 조건을 동적으로 추가 -->
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</sql>
</mapper>`
위의 예제에서는 <include>
요소를 사용하여 동적 SQL을 조합합니다. <sql>
태그에 필터 조건을 동적으로 추가하고, <include>
에서 이를 참조합니다. 필터 조건은 username
및 email
파라미터 값에 따라 동적으로 추가됩니다.
- **
요소를 사용한 동적 SQL 조합**:
<!-- UserMapper.xml -->
<mapper namespace="com.example.UserMapper">
<select id="getUserWithFilters" resultType="User">
SELECT * FROM users
<where>
<!-- 필터 조건을 동적으로 추가 -->
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
</mapper>`
위의 예제에서는 <where>
요소를 사용하여 동적 SQL을 조합합니다. <where>
태그 내에서 필터 조건을 동적으로 추가할 수 있으며, 조건이 필요하지 않은 경우 불필요한 AND
를 자동으로 처리합니다.
- **
요소를 사용한 동적 SQL 조합**:
<!-- UserMapper.xml -->
<mapper namespace="com.example.UserMapper">
<update id="updateUser" parameterType="User">
UPDATE users
<set>
<if test="username != null">
username = #{username},
</if>
<if test="email != null">
email = #{email},
</if>
</set>
WHERE user_id = #{userId}
</update>
</mapper>`
위의 예제에서는 <set>
요소를 사용하여 동적 SQL을 조합하여 업데이트 쿼리를 작성합니다. <if>
태그 내에서 필드를 동적으로 설정하고, 필드가 null이 아닌 경우에만 업데이트합니다.
이러한 동적 SQL 요소를 사용하면 다양한 상황에서 SQL 쿼리를 조합할 수 있으며, 필요한 조건에 따라 동적으로 SQL을 변경할 수 있습니다.