zoukankan      html  css  js  c++  java
  • MyBatis(3.2.3)

    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.

  • 相关阅读:
    csharp:Validate email address using C#
    Sql:SQL Server CREATE SEQUENCE statement
    机器学习实战---SVD简化数据
    机器学习实战---PCA降维
    机器学习实战---使用FP-growth算法来高效发现频繁项集
    机器学习实战---使用Apriori算法进行关联分析
    机器学习实战---集成学习AdaBoost算法
    支持向量机核函数的实现
    支持向量机SMO算法实现(注释详细)
    帧缓冲
  • 原文地址:https://www.cnblogs.com/huey/p/5231965.html
Copyright © 2011-2022 走看看