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.
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