Tuesday, April 16, 2013

Using String IN Clause for MyBatis




Recently, I came across an issue where I had to use IN clause with String in MyBatis.
We cannot use it by default because MyBatis assumes it as a single string and so, we don’t get the expected result.
After searching for some time, I was finally able to implement it using MyBatis as shown below.
Event Sql Map
<mapper namespace="monitor">
….
….
<select id="CountEvents" parameterType="map" resultType="java.lang.Integer">
                                select count(*) as value
                                from TABLE
                                <where>
                                                <if test="list != null">
                                                                EVENT_STATUS IN
                                                                <foreach item="itemList" index="index"
                                                                                 collection="list"
                                                                                open="(" separator=","
                                                                                close=")">
                                                                                #{itemList}
                                                                </foreach>
                                                </if>
                                </where>
                </select>

Invocation 
moSession.selectOne(fsSqlName, foQueryParameters);
        where
moSession  = org.apache.ibatis.session.SqlSession
               fsSqlName = monitor. CountEvents
               foQueryParameters = List containing Strings to be included 
                                                       inside IN clause( itemList  )
                                fsStatus = A,B,C ( for below case ) 
                                String loItem[]  = null;
                                List itemList = null;        
                                 if(!StringUtils.isEmpty(fsStatus ))
                                  { 
                                                 loItem = fsStatus.split(",");
                                                 itemList  = Arrays.asList(loItem);
}

No comments:

Post a Comment