在MyBatis中,我們可以使用foreach標簽來遍歷集合,并在SQL語句中使用集合的元素。以下是一些MyBatis集合遍歷與操作的技巧:
<select id="selectUsersByIds" parameterType="java.util.List" resultType="User">
SELECT * FROM users WHERE id IN
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
<select id="selectUsersByMap" parameterType="java.util.Map" resultType="User">
SELECT * FROM users WHERE
<foreach collection="map.keySet()" item="key" separator="AND">
${key} = #{map[key]}
</foreach>
</select>
<select id="insertUsersBatch" parameterType="java.util.List">
INSERT INTO users (name, age) VALUES
<foreach collection="list" item="user" index="index" separator=",">
<if test="index != 0">
,
</if>
(#{user.name}, #{user.age})
</foreach>
</select>
<update id="updateUsersBatch" parameterType="java.util.List">
<foreach collection="list" item="user" separator=";">
UPDATE users SET age = #{user.age} WHERE id = #{user.id}
</foreach>
</update>
<select id="selectUsersByCondition" parameterType="User" resultType="User">
SELECT * FROM users
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
<if test="ids != null and ids.size() > 0">
AND id IN
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
通過上述技巧,我們可以方便地在MyBatis中遍歷集合并在SQL語句中操作集合的元素,實現靈活且高效的數據操作。