我正在尝试使用 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>
奇迹般有效。