如何在 MyBatis foreach 中遍历 HashMap? [英] How to Iterate through HashMap in MyBatis foreach?

查看:29
本文介绍了如何在 MyBatis foreach 中遍历 HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 mybatis 中生成如下的 sql.

I'm trying to produce a sql which is as below in mybatis.

SELECT COL_C
FROM TBLE_1
WHERE (COL_A, COL_B) in ( ('kp','kar'),('srt','sach'));

我的输入参数类型是HashMap.现在如何从映射器 xml 文件生成 SQL.下面的代码抛出异常,表示 map 评估为 null.

And my input parameter type is HashMap. Now How do I generate SQL from mapper xml file. The below code throws exception saying map evaluated to null.

<select id="selectCOLC" parameterType="java.util.HashMap" resultType="String">
    SELECT COL_C
    FROM TBLE_1
    WHERE (COL_A, COL_B) in 
    <foreach item="item" collection="#{map.keySet()}" open="((" separator="),(" close="))">
        #{item},#{item.get(item)}
    </foreach>
</select>

另一种方法是创建一个具有键值字段的类,创建一个对象列表,然后将 parameterType 作为 list 传递,如下所示.

One of the other approach is to create a class with key value fields, create a list of object and then pass the parameterType as list which would look like following.

<select id="selectCOLC" parameterType="list" resultType="String">
        SELECT COL_C
        FROM TBLE_1
        WHERE (COL_A, COL_B) in 
        <foreach item="item" collection="list" open="((" separator="),(" close="))">
            #{item.getKey()},#{item.getVal()}
        </foreach>
    </select>

但是有没有办法让我的映射器为第一种方法工作?除了将查询更改为 union

But is there any way to my mapper work for the first approach? other than changing the query to union

推荐答案

此解决方案自 3.2 版起不起作用 - 请参阅 问题 #208

This solution doesn't work since version 3.2 - see more in Issue #208 !

我终于找到了 HashMap 的解决方案

Finally I've the solution for HashMap

我应该使用 entrySet() 以使其可迭代

I Should use entrySet() in order to make it iteratable

<select id="selectCOLC" parameterType="map" resultType="kpMap">
    SELECT COL_C
    FROM TBLE_1
    WHERE (COL_A, COL_B) in 
    <foreach item="item" collection="entries.entrySet()" open="((" separator="),(" close="))">
        #{item.key},#{item.value}
    </foreach>
</select>

我面临的另一个问题是参数名称没有被注入,因此添加了 @Param 注释

One more Isue I was facing parameter name was not getting injected, Hence added @Param annotation

因此映射器界面如下所示.

Hence mapper interface looks like below.

List<TblData> selectCOLC(@Param("entries")
            HashMap<String, String> entries)

这篇关于如何在 MyBatis foreach 中遍历 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆