Fork me on GitHub

mybatis存储过程实现二,简单根据用户名和分页参数进行查询,返回总数和分页数据

1. 首先看一下数据库要完成的存储过程(我用的数据库是DBeaver,这里也给出Navicat for Mysql中的存储过程实现,两个不同软件代码实现不太一样)

Navicat for Mysql中存储过程代码:

-- 第二个存储过程
-- 简单根据用户名和分页参数进行查询,返回总数和分页数据
delimiter $
drop procedure if exists `select_user_page`;
create procedure `select_user_page`(
    IN userName VARCHAR(50),
    IN _offset BIGINT,
    IN _limit BIGINT,
    OUT total BIGINT
)
BEGIN
--     查询数据总数
select count(*) INTO total 
from sys_user
where user_name like concat('%',userName,'%');
-- 分页查询数据
select *
from sys_user
where user_name like concat('%',userName,'%')
limit _offset, _limit;
END $
DELIMITER ;

执行后出现存储过程函数:

 

 

 DBeaver中存储过程代码:

create procedure `select_user_page`(
    IN userName VARCHAR(50),
    IN _offset BIGINT,
    IN _limit BIGINT,
    OUT total BIGINT
)
BEGIN
--     查询数据总数
select count(*) INTO total 
from sys_user
where user_name like concat('%',userName,'%');
-- 分页查询数据
select *
from sys_user
where user_name like concat('%',userName,'%')
limit _offset, _limit;
END
drop procedure if exists `select_user_page`;

注意:这里务必注意,先执行第一部分代码在执行第二部分的代码,不然执行过程会出如下错误:

执行完毕后会出现相应的存储过程:

              

 这样,第一步基础就打好了。(千万注意,在实现mybatis之前必须要实现此存储过程,不然就会出现如下错误:### Cause: java.sql.SQLException: Parameter number 2 is not an OUT parameter,这个问题折磨了我两天,头秃,难过到窒息,最后实现了此存储过程后报错才消失)

第一步基础打好了之后,接下来进行java代码配置。

2. UserMapper.xml中代码:

<select id="selectUserPage" statementType="CALLABLE"
            useCache="false" resultMap="userMap">
        {
        call select_user_page
        (
        #{userName,mode = IN},
        #{_offset,mode = IN},
        #{_limit,mode = IN},
        #{total,mode = OUT, jdbcType = BIGINT}
        )
        }
    </select>

3. 接口如下:

/*
    * 使用存储过程分页查询
    * */
    List<SysUser> selectUserPage(Map<String,Object> params);

4. 测试代码如下:

@Test
    public void testSelectUserPage(){
        SqlSession sqlSession = getSqlSession();
        try{
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            Map<String,Object> params = new HashMap<String, Object>();
            params.put("userName" , "ad");
            params.put("offset" , 0);
            params.put("limit" , 0);
            List<SysUser> userList = userMapper.selectUserPage(params);
            Long total = (Long)params.get("total");
            System.out.println("总数:" + total);
            for (SysUser user:userList
                 ) {
                System.out.println("用户名:" + user.getUserName());
            }

        }finally {

            sqlSession.close();
        }

    }

测试结果如下:

 至此,第二个存储过程结束。

posted @ 2020-12-24 16:42  叶语婷  阅读(748)  评论(0编辑  收藏  举报