June 16, 2010

Using hashmap as resultType in MyBatis

If you have an SQL statement like the following, which you don't necessarily need to retrieve into a Java Bean, you can use MyBatis' resultType="hashmap" attribute on your select statement.

The MyBatis documentation says the following:

"Such a statement simply results in all columns being automatically mapped to the keys of a HashMap, as specified by the resultType attribute."

What this actually means is for each row that is returned by your SQL statement, a HashMap will be created which will store the column name and the associated value of the field.

To illustrate

If you have the following table called cars

car_id car_make car_model car_color
22 Nissan Altima Blue
40 Jaguar X6 Green
61 BMW 328i Black
81 Audi R8 Silver

And your mapper file contain this SQL statement:

<select id="selectCars" resultType="hashmap">
 select car_id, car_model, car_color
 from cars 
 order by car_id

When you run the following code:

ArrayList<HashMap<String,Object>> results = (ArrayList<HashMap<String,Object>>)session.selectList("com.yourproject.package.TestMappers.sqlStatementX");

loop through each row returned
each key will be the column_name
each value will be the field value for that row and column
for(HashMap<String,Object> row : results){

    log.info("car id: " + row.get("car_id"));
    log.info("car model: " + row.get("car_model"));
    log.info("car color: " + row.get("car_color"));


You would get following output

22 Altima Blue
40 X6 Green
61 328i Black
81 R8 Silver