6

我正在尝试使用 MyBatis 3.0.6 找出以下问题的解决方案:

我需要基于一系列参数构建一个动态选择语句,其中一个参数是HashMap<String, List<String>>. 挑战在于弄清楚如何让 MyBatis 迭代外部foreach循环中的所有键,以及迭代内部循环中值列表的元素。

为了说明,假设我的名为filter的哈希映射参数包含每个国家(国家代码作为键)的状态(状态代码列表,每个列表都是值),如下所示:

'US' -> {'CO','NY','MI','AZ'};
'CA' -> {'ON','BC','QC'}

我需要我的动态 SQL 看起来像这样(以非常简化的形式):

SELECT *
FROM  Table1
WHERE ... some static criteria goes here...
      AND RowId IN (SELECT RowId FROM Table2 WHERE Country = 'US' AND State IN ('CO','NY','MI','AZ')
      AND RowId IN (SELECT RowId FROM Table2 WHERE Country = 'CA' AND State IN ('ON','BC,'QC')

我想我的映射器 XML 应该是这样的:

<select id="getData" resultType="QueryResult">
SELECT *
FROM  Table1
WHERE ... some static criteria goes here...
     <if test="filter != null">
         <foreach item="country" index="i" collection="filter" separator="AND">
             RowId IN (SELECT RowId 
                       FROM Table2 
                       WHERE Country = #{country} AND State IN
             <foreach item="state" index="j" collection="country.states" separator="," open="(" close=")">
                 #{state}
             </foreach>
         </foreach>
     </if>
</select>

所以问题是,让country.states在嵌套的foreach循环中迭代的正确语法是什么?


更新

经过一番修改后,我无法让 MyBatis 很好地使用基于 HashMap 的方法,所以我最终添加了一个将多个值映射到其父值的新类,然后将这些对象的列表传递给 MyBatis。使用上面的国家/州示例,该类如下所示:

public class Filter {
   private String country;
   private ArrayList<String> states;

   // ... public get accessors here ...
}

DAO方法:

public void QueryResult[] getResults( @Param("criteria") List<Filter> criteria) ...

和 MyBatis 映射:

<select id="getData" resultType="QueryResult">
SELECT *
FROM  Table1
WHERE ... some static criteria goes here...
     <if test="criteria!= null">
         <foreach item="filter" index="i" collection="criteria" separator="AND" open="AND">
             RowId IN (SELECT RowId 
                       FROM Table2 
                       WHERE Country = #{filter.country} AND State IN
             <foreach item="state" index="j" collection="filter.states" separator="," open="(" close=")">
                 #{state}
             </foreach>
         </foreach>
     </if>
</select>

奇迹般有效。

4

3 回答 3

3

实际上,您可以使用国家/地区值在过滤器映射中查找它,并使其像您最初拥有的那样工作。在第二个循环中,您的集合将被定义为filter.get(country)并且应该是好的。这当然是考虑到我正确地解释了你的问题。

于 2012-10-11T12:32:51.743 回答
1

我有一些东西要作为地图插入,其中每个地图键都映射到一个列表。我以这种方式编写了查询。

INSERT INTO TB_TEST (group_id, student_id) VALUES
<foreach collection="idMap.entrySet()" item="element" index="index" separator=",">
         <foreach collection="element.value" item="item" separator="," > 
            ( #{element.key}  #{item} )     
         </foreach> 
    </foreach>
于 2015-03-27T12:54:22.740 回答
1

到目前为止,我可以做到这一点。

<foreach collection="myMap" index="key" item="value">
  <foreach collection="value" item="element">
    ... = #{key} ...
    ... = #{element})
  </foreach>
</foreach>
于 2017-12-29T07:47:04.547 回答