在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语句中操作集合的元素,实现灵活且高效的数据操作。