天天看点

MyBatis从入门到放弃五:调用存储过程(SQLServer2012)

前言

      如果是相对于复杂的SQL逻辑我们肯定是基于存储过程开发,这篇学习下执行存储过程,调用存储过程如果参数较多我们可以创建parameterMap。

搭建开发环境

      开发环境和上篇文章保持相同

创建存储过程

     存储过程执行一对多的关联查询

MyBatis从入门到放弃五:调用存储过程(SQLServer2012)

   修改mapper.xml

<select id="testProc" parameterType="int" resultMap="authorResultMap">
        exec usp_getAuthorBlogsById #{id}
    </select>      

单元测试

@Test
    public void testProc(){
        SqlSession sqlSession=null;
        try{
            sqlSession=sqlSessionFactory.openSession();

            Author author = sqlSession.selectOne("com.autohome.mapper.Author.testProc",1);
            System.out.println("作者信息 id:"+author.getId()+",name:"+author.getName());
            System.out.println("作者博客:");
            for(Blog blog:author.getBlogs()){
                System.out.println("id:"+blog.getId()+",title:"+blog.getTitle()+",category:"+blog.getCategory());
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }
      

附单元测试截图

MyBatis从入门到放弃五:调用存储过程(SQLServer2012)