使用动态别名准备ibatis查询

时间:2014-06-18 10:26:53

标签: java sql ibatis

我需要使用ibatis创建一个查询,其中包含以下内容:

SELECT code,name,info0,info1,.... FROM TABLENAME;

info0,info1,....可以是任何数字,我需要动态准备。

code,name,info0,info1 ....都是别名。

IBATIS QUERY

<select id="getReferenceDataListByReferenceMasterInfo"
    parameterType="com.util.ReferenceMetaData" resultMap="refdatalist-result">

    SELECT code,name,

    <if test="infoNameList != null">
        <foreach item="item" index="index" separator="," collection="infoNameList">
            #{'info'${index}}
        </foreach>
    </if>

    FROM
    (
        SELECT
        trim(${codeColumnName}) as code,

        <choose>
            <when test="nameColumnName != null">
                ${nameColumnName} as name,
            </when>
            <otherwise>
                null as name,
            </otherwise>
        </choose>
        <choose>
            <when test="infoNameList != null">
                <foreach item="item" index="index" collection="infoNameList">
                    ${item} as info${index},
                </foreach>
            </when>
        </choose>
        row_number() over (order by ${codeColumnName}) as ROWNUM

        FROM UREF.${tableName}

    )
</select>

如果我们将别名明确指定为:

,则上述查询工作正常
SELECT code,name,info0,info1,info2 FROM (...

1 个答案:

答案 0 :(得分:1)

得到答案.....

代码看起来像这样,

<if test="infoNameList != null">
    <foreach item="item" index="index" separator="," collection="infoNameList">
        info${index}
    </foreach>
</if>