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.

  • 相关阅读:
    Less35、Less36【无闭合注入,mysql_real_escape_string()】
    Less34【POST方式宽字符注入】
    Less29,30,31【jsp环境搭建、WAF】
    Less28、28a【select、union、空格过滤】
    Less27、27a【select、union、空格过滤】
    Less26,26a【空格符号过滤】
    Less25,25a【and/or过滤】
    Less24【二次注入】
    Less23【报错注入】
    NFC
  • 原文地址:https://www.cnblogs.com/huey/p/5231965.html
Copyright © 2011-2022 走看看