⚡動的SQL
条件に基づいて動的にSQLを構築するための強力な機能
主要な動的SQL要素:
if条件
<select id="findUsers" resultType="User">
SELECT * FROM users WHERE 1=1
<if test="name != null">
AND name LIKE #{name}
</if>
<if test="email != null">
AND email = #{email}
</if>
</select>
choose, when, otherwise
<select id="findUser" resultType="User">
SELECT * FROM users
<choose>
<when test="id != null">
WHERE id = #{id}
</when>
<when test="name != null">
WHERE name = #{name}
</when>
<otherwise>
WHERE active = true
</otherwise>
</choose>
</select>
foreach
<select id="getUsersByIdList" resultType="User">
SELECT * FROM users
WHERE id IN
<foreach item="item" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
💡ベストプラクティス
効率的なMyBatis使用のためのヒント:
- 適切なキャッシュ戦略を使用する
- 複雑なクエリにはResultMapを使う
- トランザクション管理に注意する
- パラメータにTypedハンドラを使用する
キャッシュの設定例
Mapper XML
<cache
eviction="LRU"
flushInterval="60000"
size="512"
readOnly="true"/>
ResultMap例
複雑なマッピング
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
<result property="name" column="user_name"/>
<result property="email" column="user_email"/>
<association property="profile"
javaType="Profile">
<id property="id" column="profile_id"/>
<result property="bio" column="bio"/>
</association>
</resultMap>