I have a java class like this:
public class Team {
private HashMap<String, User> users;
private int id_team;
private String nome;
...
}
And an xml file like this:
<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.
You're not using the HashMap
correctly. 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.
What you want to do is to map IDs to user objects
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>
. 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.
I resolved using
private Arraylist<User> users;
and
<collection property="users" javaType="ArrayList">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.