使用来自 nativeQuery 的多个参数填充 Map 值

问题描述 投票:0回答:1

出于好奇,我想知道是否可以用我的查询结果填充

Map<Integer, ArrayList<String>>
...

我有以下问题:

 SELECT DISTINCT code, email FROM user;

这会导致同一代码的多个电子邮件记录,例如:

| CODE     | EMAIL                     |
| -------- | --------                  |
| 1        | [email protected]          |
| 1        | [email protected]     |
| 2        | [email protected] |

方法(应该返回一些东西):

    @Override
    public Map<Integer, ArrayList<String>> returnCodeEmail() {
        StringBuilder sql = "SELECT DISTINCT code, email FROM user";
        return new HashMap();
    }

我试过:

 return (Map<Integer, ArrayList<String>>) entityManager
       .createNativeQuery(sql.toString())
       .getResultList()
       .stream()
       .collect(Collectors.toMap(
             t -> ((Tuple) t).get(0), 
             t -> ((Tuple) t).get(1)
        ));

但它似乎无法按预期填充列表...

我怎样才能确保我的地图有一个 Key,即

code
和一个
 emails
的值列表,如表中所示?

提前致谢:)

java collections entitymanager
1个回答
0
投票

我得到了一个解决方案,多亏了 this 前一段时间的帖子!

所以,简单地说......一个元组结构可以很好地工作或这样的查询,返回对象真的很容易管理。

然后只需过滤掉值和它们关联的键,将值添加到 Map 中,它们的键已经在其中,如果不存在,则将键添加到列表中。

代码:

   List<Tuple> result = query.getResultList();
   Map<Integer, List<String>> finalObject = new HashMap<>();
   List<String> emailsValue;
   BigInteger codeKey;

   for (Tuple t : result) {
       if (t.get("id", BigInteger.class) != null) {
           codeKey = t.get("id", BigInteger.class);
           if (finalObject.containsKey(codeKey.intValue())) {
               emailsValue = finalObject.get(codeKey.intValue());
               emailsValue.add(t.get("email", String.class));
       } else {
           emailsValue = new ArrayList<>();
           emailsValue.add(t.get("email", String.class));
           finalObject.put(codeKey.intValue(), emailsValue);
       }
   }
© www.soinside.com 2019 - 2024. All rights reserved.