Dashboard > iBATIS DataMapper > Home > Frequently Asked Questions > How do I get a Map of results instead of a List
How do I get a Map of results instead of a List
Added by Nathan Maves, last edited by Chadwick on Jun 21, 2009  (view change) show comment
Labels: 
(None)


The following section will explain in detail how to use the queryForMap().

The queryForMap()'s are most useful when you need to work with the result of a query. In the example below I will use a query that return Student objects as a result. Lets start with the Student class.

Student.java
public class Student implements java.io.Serializable {
    
    private String id, firstName, lastName;
    
    public String getId() {
    return id;
    }
    
    public void setId(String id) {
    this.id = id;
    }
    
    public String getFirstName() {
    return firstName;
    }
    
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }
    
    public String getLastName() {
    return lastName;
    }
    
    public void setLastName(String lastName) {
    this.lastName = lastName;
    }

And now the SqlMap ....

<resultMap id="studentResult" class="com.domain.Student">
    <result column="id" property="id" />
    <result column="first_name" property="firstName" />
    <result column="last_name" property="lastName" />
    </resultMap>
    
    <select id="getAllStudents" resultMap="studentResult">
    select
    *
    from students
    </select>

Now that the basics are out of the way query away!

Lets say that you need to do some fast serching on the returned students. The best way is to have a Map of the Student objects to their id's.

This is where the queryForMap() comes into play. There are two different options and both will be dicussed. The first is perfect for the example given above.

public Map getAllStudents() {
    
    Map<String, Student> studentsMap = queryForMap("getAllStudents", null, "id");
    
    Student student = studentsMap.get("123456");
    
    ...
    }

You can see that the third parameter in the call looks for the property "id" in the result map and then creates the map with that property as the key.

The second option allow you to specify both the key and the value.

Map<String, String> studentsMap = queryForMap("getAllStudents", null, "id", "firstName");

The above code will return a Map with the id as the key and the firstName as the value.

There are many other uses for these method so feel free to add them on


Site running on a free Atlassian Confluence Open Source Project License granted to OSS. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.5 Build:#811 Jul 25, 2007) - Bug/feature request - Contact Administrators