天天看點

mybatis 之 <foreach>标簽使用篇關于mybatis 的使用,希望可以給大家帶來幫助

關于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>
           

繼續閱讀