首页 > 其他 > 详细

MyBatis(3.2.3) - Custom ResultSet processing using ResultSetHandler

时间:2016-03-01 18:43:41      阅读:199      评论:0      收藏:0      [点我收藏+]

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.

MyBatis(3.2.3) - Custom ResultSet processing using ResultSetHandler

原文:http://www.cnblogs.com/huey/p/5231965.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!