Ciro
Ciro

Reputation: 263

hashmap resultmap in mybatis

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.

Upvotes: 2

Views: 8206

Answers (2)

Ciro
Ciro

Reputation: 263

I resolved using

private Arraylist<User> users;

and

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

Upvotes: -1

chiastic-security
chiastic-security

Reputation: 20520

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.

Upvotes: 2

Related Questions