开发者

How to use an IN clause in iBATIS?

I'm using iBATIS to create select statements. Now I would like to implement the following SQL statement with iBATIS:

SELECT * FROM table WHERE col1 IN ('value1', 'value2');

With the following approach, the statement is not prepared correctly and no result returns:

SELECT * FROM table WHERE col1 IN #listOfValues#;

iB开发者_开发知识库ATIS seems to restructure this list and tries to interpret it as a string.

How can I use the IN clause correctly?


Here's a blog post that answers your question:

iBatis: Support for Array or List Parameter with SQL IN Keyword

<select id="select-test" resultMap="MyTableResult" parameterClass="list">
select * from my_table where col_1 in
  <iterate open="(" close=")" conjunction=",">
   #[]#
  </iterate>
</select>

And in Java you should pass in a java.util.List. E.g.

List<String> list = new ArrayList<String>(3);
list.add("1");
list.add("2");
list.add("3");
List objs = sqlMapClient.queryForList("select-test",list);


How about

<select id="foo" parameterClass="Quuxly" resultClass="Flobitz">
    select * from table
    <dynamic prepend="where col1 in ">
        <iterate property="list_of_values" open="('" close="')" conjunction=",  ">
            #list_of_values[]#
        </iterate>
    </dynamic>
</select>


Or:

<select id="select-test" resultMap="MyTableResult" parameterClass="list"> 
 select * from table where
 <iterate property="list" conjunction="OR">
  col1 = #list[]#
 </iterate>
</select>


<select id="select-test" parameterClass="list"resultMap="YourResultMap">
     select * from table where col_1 IN 
     <iterate open="(" close=")" conjunction=",">
      #[]#
    </iterate>
</select>


An old question, but for the users of MyBatis, the syntax is a bit different:

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

Refer to the guide in here.


You can use it like this:

<select id="select-test" resultMap="MyTableResult" >
select * from my_table where col_1 in
 $listOfValues$
</select>

use the $ in the IN statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜