Java 如何在 iBATIS 中使用 IN 子句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1637825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use an IN clause in iBATIS?
提问by guerda
I'm using iBATISto create select statements. Now I would like to implement the following SQL statement with iBATIS:
我正在使用iBATIS创建选择语句。现在我想用 iBATIS 实现以下 SQL 语句:
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#;
iBATIS seems to restructure this list and tries to interpret it as a string.
iBATIS 似乎重组了这个列表,并试图将其解释为一个字符串。
How can I use the IN clause correctly?
如何正确使用 IN 子句?
采纳答案by jitter
Here's a blog post that answers your question:
这是一篇回答您问题的博客文章:
iBatis: Support for Array or List Parameter with SQL IN Keyword
iBatis:支持带有 SQL IN 关键字的数组或列表参数
<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.
而在 Java 中,你应该传入一个 java.util.List。例如
List<String> list = new ArrayList<String>(3);
list.add("1");
list.add("2");
list.add("3");
List objs = sqlMapClient.queryForList("select-test",list);
回答by Jonathan Feinberg
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>
回答by bastola
Or:
或者:
<select id="select-test" resultMap="MyTableResult" parameterClass="list">
select * from table where
<iterate property="list" conjunction="OR">
col1 = #list[]#
</iterate>
</select>
回答by iamxhu
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.
在 IN 语句中使用 $。
回答by Venkat R Paruchuri
<select id="select-test" parameterClass="list"resultMap="YourResultMap">
select * from table where col_1 IN
<iterate open="(" close=")" conjunction=",">
#[]#
</iterate>
</select>
回答by Itaypk
An old question, but for the users of MyBatis, the syntax is a bit different:
一个老问题,但是对于 MyBatis 的用户来说,语法有点不同:
<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.