![](/img/trans.png)
[英]How to convert List to Map and make the map key the object's attributes
[英]How to convert a List of Map that has object as key to 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 作为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>>
转换为 map 以获取键值对?
有问题的 HQL 实际上是返回List<Map<String, Object>>
SELECT new map(key(m), value(m) ) from User u join u.shopRoleMap m where u.usEmail = :email
新 map的语法基本上需要这些值。 因此,当将 key(m) 和 value(m) 传递给它时, key(m) 和 value(m) 将被视为 Map 值。 map的关键基本上是索引值(0,1,2,..)
You can read more about it in the Hibernate Documentation - https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#hql-select-clause
因此,您应该将 HQL 替换为
SELECT entry(m) from User u join u.shopRoleMap m where u.usEmail = :email
这应该返回List<Map.Entry<Shop,Role>>可以迭代以获得正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.