ibatis에서 map 사용하기.

DB 2007. 10. 3. 02:50

ibatis에서 다들 list를 쓰고 있는데, map도 지원된다.

queryForMap() 메소드를 활용하면 Map을 리턴한다.








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" />

<select id="getAllStudents" resultMap="studentResult">
from students

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



Posted by '김용환'

댓글을 달아 주세요