Search code examples
javapostgresqlibatis

ibatis use IN instead of OR


I have following query in my sql mapping file, it is using OR in the generated SQL query for FIELD3. It is a List of Integer

<select id="myCriteria" parameterClass="mySearchCriteria" resultMap="generated_MyResult">
        select * from MY_TABLE where MY_TABLE.FIELD1 = 1
        <dynamic>
            <isNotNull prepend="and" property="field2">
                MY_TABLE.FIELD2 = $field2$
            </isNotNull>

            <isNotNull prepend="and" property="field3_list">
                <iterate close=")" conjunction="or" open="(" property="meIds">
                    MY_TABLE.FIELD3= $field3_list[]$
                </iterate>
            </isNotNull>
        </dynamic>
    </select>

If I want to use IN instead of OR , iterate is removed, the below will work?

<select id="myCriteria" parameterClass="mySearchCriteria" resultMap="generated_MyResult">
        select * from MY_TABLE where MY_TABLE.FIELD1 = 1
        <dynamic>
            <isNotNull prepend="and" property="field2">
                MY_TABLE.FIELD2 = $field2$
            </isNotNull>

            <isNotNull prepend="and" property="field3_list">

                    MY_TABLE.FIELD3 IN $field3_list[]$

            </isNotNull>
        </dynamic>
    </select>

Solution

  • To use a IN clause, i would keep iterate element:

    <select id="myCriteria" parameterClass="mySearchCriteria" resultMap="generated_MyResult">
        select * from MY_TABLE where MY_TABLE.FIELD1 = 1
        <dynamic>
            <isNotNull prepend="and" property="field2">
                MY_TABLE.FIELD2 = #field2#
            </isNotNull>
            <isNotEmpty prepend="and" property="field3_list">
                MY_TABLE.FIELD3 IN
                <iterate open="(" close=")" conjunction="," property="field3_list">
                    #field3_list[]#
                </iterate>
            </isNotEmpty>
        </dynamic>
    </select>
    

    Or, if you are sure that you field3_list is never null:

    <select id="myCriteria" parameterClass="mySearchCriteria" resultMap="generated_MyResult">
        select * from MY_TABLE where MY_TABLE.FIELD1 = 1
        <dynamic>
            <isNotNull prepend="and" property="field2">
                MY_TABLE.FIELD2 = #field2#
            </isNotNull>
            <iterate open="(" close=")" conjunction="," property="field3_list" prepend="AND MY_TABLE.FIELD3 IN">
                #field3_list[]#
            </iterate>
        </dynamic>
    </select>
    

    Also, I switched your parameters from $xx$ (which refers to table name) to #xx#