简体   繁体   English

Mybatis中的哈希图结果图

[英]hashmap resultmap in mybatis

I have a java class like this: 我有一个像这样的Java类:

public class Team {
private HashMap<String, User> users;
private int id_team;
private String nome;
...
}

And an xml file like this: 和这样的xml文件:

<resultMap id="userJoinTeamResultMap" type="Team">
    <id column="id_team" property="id_team" />
    <result column="nome" property="nome" />
    <collection property="users" javaType="HashMap" >
        <id column="id_user" property="id" />
        <result column="nome_user" property="nome" />
        <result column="cognome" property="cognome" />
        <result column="email" property="email" />
    </collection>
</resultMap>

And a select that does what it have to do. 和选择,它可以做的事。 But when I try to get the values in my hashmap: 但是,当我尝试获取哈希图中的值时:

ArrayList<Team> listaTeam = getBlmTeam().getUserTeamFromCorso(jsonInput.getInt("id_corso"));
Iterator<Team> it = listaTeam.iterator();
while(it.hasNext()){
        Team t = it.next();
        Collection<String> set = t.getUsers().keySet();
        Iterator it2 = set.iterator();
        while(it2.hasNext()){
             Object k = it2.next();
             System.out.println("key:"+k.toString()+"  value:"+t.getUsers().get(k));
}}

My values are: 我的价值观是:

key:id     value:103
key:email  value:HSXB736GB
key:id     value:105
key:email  value:ZQFD4U
..

What keys are??? 什么钥匙是??? In the first team there are two users with keys 102 and 103. But every user uses the key "id", so, they are overwritten. 在第一个小组中,有两个用户具有键102和103。但是每个用户都使用键“ id”,因此它们被覆盖。

You're not using the HashMap correctly. 您没有正确使用HashMap You don't want to map 你不想地图

id -> 103
email -> HSXB736GB

etc. As you've discovered, if you do that, you'll only be able to have one user in there, because the key has to be unique, so when you add a new user, the id will be overwritten. 正如您所发现的,如果这样做,您将只能在其中拥有一个用户,因为密钥必须是唯一的,因此当您添加新用户时,该id将被覆盖。

What you want to do is to map IDs to user objects 您要做的是将ID映射到用户对象

103 -> [user instance with ID 103]
105 -> [user instance with ID 105]

This means that rather than HashMap<String,Utente> you want HashMap<Integer,Utente> . 这意味着您需要HashMap<Integer,Utente>而不是HashMap<String,Utente> HashMap<Integer,Utente> Then you can do things like 然后你可以做类似的事情

Utente someUser = ...
map.put(someUser.getId(), someUser);

and later you'll be able to retrieve the user from the map with 之后,您将可以从地图中检索用户

Utente someUser = map.get(id);

as long as you know the ID. 只要您知道ID。

I resolved using 我解决了

private Arraylist<User> users;

and

<collection property="users" javaType="ArrayList">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM