mybatis 之 <foreach>标签使用
关于mybatis 的使用
示例内容
// 这里为返回对象 tabletRoot 数据库表对应的接收对象
<resultMap id="ResultMap" type="com.exc.xy.root.tabletRoot">
<id column="TABLE_ID" property="tableId" jdbcType="NUMERIC"/>
<result column="TABLE_TYPE" property="tableType" jdbcType="NUMERIC"/>
<result column="TABLE_FIELD" property="tableField" jdbcType="VARCHAR"/>
</resultMap>
// 这里为示例 SQL
<select id="list" resultMap="ResultMap" parameterType="java.util.Map">
SELECT
TABLE_ID,
TABLE_TYPE,
TABLE_FIELD
FROM TABLE_NAME
WHERE TABLE_TYPE IN
<trim suffixOverrides=" OR TABLE_TYPE IN()">
<foreach collection="param.tableTypeList" item="item" index="index" open="(" close=")">
<if test="index != 0">
<choose>
<when test="index % 1000 == 999">) OR TABLE_TYPE IN (</when>
<otherwise>,</otherwise>
</choose>
</if>
#{item,jdbcType=NUMERIC}
</foreach>
</trim>
</select>
注意事项
这里提示一点,当 in 对应的条件过多时会影响查询效率,如果因为业务无法避免这种情况发生时,可以使用 fetchSize 来控制每次查询条数 可以在一定基础上提升效率,自己测试建议使用1000条为基准
// 以下未使用示例,由于比较懒直接粘贴上边的SQL
<select id="listExc" parameterType="java.util.Map" resultMap="ResultMap"
fetchSize="1000">
SELECT
TABLE_ID,
TABLE_TYPE,
TABLE_FIELD
FROM TABLE_NAME
WHERE TABLE_TYPE IN
<trim suffixOverrides=" OR TABLE_TYPE IN()">
<foreach collection="param.tableTypeList" item="item" index="index" open="(" close=")">
<if test="index != 0">
<choose>
<when test="index % 1000 == 999">) OR TABLE_TYPE IN (</when>
<otherwise>,</otherwise>
</choose>
</if>
#{item,jdbcType=NUMERIC}
</foreach>
</trim>
</select>