将配对列表传递给myBatis

时间:2018-11-13 23:26:48

标签: mybatis

我需要一个与MyBatis配对查询的列表:

在Mapper中:

List<Usage> getUsageByUserLanguagesAndDates(
      @Param("userLanguagePairList") List<Pair<String, String>> userLanguageMap,
      @Param("startDate") DateTime startDate,
      @Param("endDate") DateTime endDate)

列表> userLanguageMap看起来像这样:

List<Pair<String, String>> pairs = Lists.newArrayList;
pairs.add(new Pair("12345", "en-US"));
pairs.add(new Pair("23456", "en-GB"));
...

查询如下:

SELECT
    ...
    FROM
    ...
    WHERE 1=1
    AND 
    (
        (l.userid = '12345' AND ll.language_code = 'en-US') OR
        (l.userid = '23456' AND ll.language_code = 'en-GB') 
    )
   ;

我尝试将查询写为:

AND (
    <foreach item="userLanguagePair" index="index" collection="userLanguagePairList" open="" separator="," close="">
      (
        l.userid = #{userLanguagePair.first}
        AND
        ll.language_code = #{userLanguagePair.second}
      )
      OR
    </foreach>
    )

...

,但最后会有一个额外的OR:

AND 
        (
            (l.userid = '12345' AND ll.language_code = 'en-US') OR
            (l.userid = '23456' AND ll.language_code = 'en-US') OR
        )

我如何摆脱上一个“ OR”?

1 个答案:

答案 0 :(得分:2)

来自http://www.mybatis.org/mybatis-3/dynamic-sql.html

<foreach item="item" index="index" collection="list" open="(" separator="," close=")">

所以我想说你的代码应该是这样的:

...
WHERE 1=1 AND (
<foreach item="userLanguagePair" index="index" collection="userLanguagePairList" open="(" separator="OR" close=")">
    l.userid = #{userLanguagePair.first}
    AND
    ll.language_code = #{userLanguagePair.second}
</foreach>
)

但是现在我无法检查这是否会生成正确的句子。