MyBatis(3.2.3) - Custom ResultSet processing using ResultSetHandler

时间:2021-06-09 03:15:10

MyBatis provides great support with plenty of options for mapping the query results to JavaBeans. But sometimes, we may come across scenarios where we need to process the SQL query results by ourselves for special purposes. MyBatis provides ResultHandler plugin that enables the processing of the ResultSet in whatever way we like.

Suppose that we want to get the student details in a HashMap where stud_id is used as a key and name is used as a value.

For sqlSession.select() methods, we can pass an implementation of ResultHandler that will be invoked for each record in the ResultSet.

public interface ResultHandler {
void handleResult(ResultContext context);
}

Now let us see how we can use ResultHandler to process the ResultSet and return customized results.

public Map<Integer, String> getStudentIdNameMap() {
final Map<Integer, String> map = new HashMap<Integer, String>();
SqlSession sqlSession = MyBatisUtil.openSession();
try {
sqlSession.select(
"com.mybatis3.mappers.StudentMapper.findAllStudents",
new ResultHandler() {
@Override
public void handleResult(ResultContext context) {
Student student = (Student) context.getResultObject();
map.put(student.getStudId(), student.getName());
}
}
);
} finally {
sqlSession.close();
}
return map;
}

In the preceding code, we are providing an inline implementation of ResultHandler. Inside the handleResult() method, we are getting the current result object using context.getResultObject() that is a Student object because we configured resultMap="StudentResult" for the findAllStudents mapped statement. As the handleResult() method will be called for every row returned by the query, we are extracting the studId and name values from the Student object and populating the map.