如何将以对象为键的Map列表转换为Map?

3
我有一个查询仓库的代码,它将返回以下格式的Map列表:
@Query("SELECT new map(key(m), value(m) ) from User u join u.shopRoleMap m where u.usEmail = :email")
     List<Map<Shop,Role>> findByUserEmail(String email);

用户映射如下:
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    @JoinTable(name = "user_shop_role",
            joinColumns = @JoinColumn(name = "user_fk"), inverseJoinColumns = @JoinColumn(name = "role_fk"))
    @MapKeyJoinColumn(name = "shop_fk")
    private Map<Shop, Role> shopRoleMap = new HashMap<>();

在我的服务中,我需要将地图作为 Map<Shop,Role> 进行获取,以便我可以相应地获取键和值。 代码如下:

List<Map<Shop,Role>> shopRole= userRepository.findByUserEmail(email);

        for (Map<Shop,Role> map : shopRole){
            for (Map.Entry<Shop,Role> result : map.entrySet()){
                System.out.println("The key is: "+result.getKey());
                System.out.println("And the value is: "+result.getValue());
            }
        }
        }

我得到的结果有些奇怪,因为我期望 result.getKey() 给我返回 Shop 作为键,但实际上我得到的键是0和1。
The key is: 0
And the value is: Shop{id=54, sh_name='Frefdv', sh_icon='icon url', sh_description='Fashion Shop', sh_tag='metadata', uuid='99dba3d5-dfaa-446d-9649-b9b98f422f87', sh_enabled='N', created_at=2020-07-30T15:54:10, updated_at=2020-07-30T15:54:10, created_by='e0b009ef-27c2-405b-961a-86f199b15167', updated_by='e0b009ef-27c2-405b-961a-86f199b15167'}
The key is: 1
And the value is: Role{id=0, roleName='ADMIN'}
The key is: 0
And the value is: Shop{id=55, sh_name='fnhfh', sh_icon='icon url', sh_description='Fashion Shop', sh_tag='metadata', uuid='e3ccdbdf-aad2-43ba-8331-91b2c2c01853', sh_enabled='N', created_at=2020-07-30T15:54:23, updated_at=2020-07-30T15:54:23, created_by='e0b009ef-27c2-405b-961a-86f199b15167', updated_by='e0b009ef-27c2-405b-961a-86f199b15167'}
The key is: 1
And the value is: Role{id=0, roleName='ADMIN'}

我该如何将这个 List<Map<Shop,Role>> 转换为一个键值对的映射表?

我没有给你的问题投反对票。但是它被标记了,因为它有3个问题,为了让帖子更加专注,只留下一个问题是指南之一。而且如果jpa返回字符串,java流在这里无法做任何事情,所以最好将其删除。 - Kavithakaran Kanapathippillai
如果你的shopRole实际上是一个List<Map<Shop, Role>>,那么你的嵌套for循环和流是没问题的。根据你的输出和错误信息,我认为可以安全地假设shopRole实际上是其他类型。不幸的是,我对JPA/HQL不够熟悉,无法在这里提供帮助,但我建议你使用调试器查看你实际得到了什么,并从那里开始工作。 - Rick
@Rick,很遗憾推断出的映射键不是Shop类型。不知道代码出了什么问题。 - Fred Kibuchi
@KavithakaranKanapathippillai,感谢你的提醒。我已经编辑过了,让问题更加专业。 - Fred Kibuchi
你能分享一下关于 UsershopRoleMap 的相关 JPA 注解吗? - PrasadU
@PrasadU 添加了 JPA 注解,用于映射实体 Shop 和 Role。 - Fred Kibuchi
1个回答

1
这里的HQL实际上返回了List<Map<String, Object>>
SELECT new map(key(m), value(m) ) from User u join u.shopRoleMap m where u.usEmail = :email

new map的语法基本上期望值。因此,当key(m)和value(m)被传递给它时,key(m)以及value(m)都被视为Map值。映射的键基本上是索引值(0,1,2,..)

您可以在Hibernate文档中阅读更多信息 - https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#hql-select-clause

enter image description here

所以,你应该将你的HQL替换为:
SELECT entry(m) from User u join u.shopRoleMap m where u.usEmail = :email

这应该返回 List<Map.Entry<Shop,Role>>,可以迭代以获取正确的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接