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.

  • 相关阅读:
    卷积神经网络入门(1) 识别猫狗
    lumen 获得当前uri 如/xxx/{id}
    React ES5 (createClass) 和 ES6 (class)
    lumen 单元测试
    mysql 高级语法手记
    react手记(componentWillMount,componentDidMount等)
    lumen 事件
    PDO drivers no value in Windows
    BindingNavigator操作DatagridView的数据
    <input type="hidden" id="haha" name="wang" value="xiaodong" />
  • 原文地址:https://www.cnblogs.com/huey/p/5231965.html
Copyright © 2011-2022 走看看