Question

I have to build a IN condition using MyBatis where have to pass a list of PARENT_VALUES to be obtained based on the foreach loop below....

I tried but unable to resolve this. I am not sure if

Values Passed are:

Map input = new HashMap();
input.put("somedata");
List<String> inConditionList = new ArrayList<String>();
inConditionList.add("P1");
inConditionList.add("P2");
input.put(inConditionList);
sqlSessionTemplate.selectList("getNameAgeDetails", input);

Required SQL:

 SELECT P.NAME, P.AGE
   FROM PERSON_DETAILS P
   WHERE SOMECOLUMN is NULL AND DATA IN
   (SELECT DATA FROM PARENT_TABLE WHERE PARENT_VALUE IN ("P1, "P2"))
 ORDER BY P.NAME
  FETCH FIRST 10 ROW ONLY

MyBatis Mapper SQL:

<select id="getNameAgeDetails" parameterType="map" resultMap="someResultMap">
    <![CDATA[
        SELECT P.NAME, P.AGE
        FROM PERSON_DETAILS P
        WHERE
         SOMECOLUMN is NULL
        AND DATA IN
          (SELECT DATA
          FROM PARENT_TABLE
          WHERE PARENT_VALUE IN 
         <FOREACH item="item"  index="index" collection="list" separator="," open="(" close=")"> 
                ${item}
            </FOREACH>  
          )
          ORDER BY P.NAME
          FETCH 
            FIRST 10 ROW ONLY 
    ]]>
  </select>

Below is the Error I am getting when I try to run my Unit TestCases:

### The error occurred while setting parameters
### SQL: SELECT P.NAME, P.AGE
            FROM PERSON_DETAILS P
            WHERE
             SOMECOLUMN is NULL
            AND DATA IN
              (SELECT DATA
              FROM PARENT_TABLE
              WHERE PARENT_VALUE IN <FOREACH item="item"  index="index" collection="list" separator="," open="(" close=")">                      ?              </FOREACH>             
### Cause: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=PARENT_VALUE IN 
            <foreach it;TION
          WHERE;<space>, DRIVER=3.63.75
; bad SQL grammar []; nested exception is com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=PARENT_VALUE IN 
Was it helpful?

Solution

Your Select statement would like something like this

<select id="getNameAgeDetails" parameterType="map" resultMap="someResultMap">
        SELECT P.NAME, P.AGE
        FROM PERSON_DETAILS P
        WHERE
         SOMECOLUMN is NULL
        AND DATA IN
          (SELECT DATA
          FROM PARENT_TABLE
          WHERE PARENT_VALUE IN 
         <FOREACH item="item"  index="index" collection="list" separator="," open="(" close=")"> 
                ${item}
            </FOREACH>  
          )
          ORDER BY P.NAME
          FETCH 
            FIRST 10 ROW ONLY 
  </select>

OTHER TIPS

I agree with Karthik Prasad and if you remove CDATA and have sth like

a_column>=6 AND b_column<10

you must do the XML escape just as below:

a_column &gt;= 6 AND b_column &lt; 10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top