mybatis入门篇:存储过程的操作

时间:2024-01-03 23:01:38

1、无ResultType/ResultMap查询

先定义一个查询的存储过程:

DELIMITER //
CREATE PROCEDURE `select_user_by_id`( IN userId BIGINT, OUT userName VARCHAR(), OUT headImg BLOB, OUT createTime DATETIME )
BEGIN
SELECT user_name, head_img, create_time
INTO userName, headImg, createTime
FROM user
WHERE id=userId;
END
//
DELIMITER ;

编写mapper接口和xml:

public interface UserMapper {
    void selectUsersById(User user);
}

注:存储过程不支持缓存,为了避免缓存配置出错,此处加上useCache=“false”。另外,OUT的参数需要悉数加上jdbcType,因为IN模式下,mybatis指定了jdbcType,同时,对于BLOB格式的参数,需要加上javaType,在mybatis映射的java类中,不建议使用基本类型。blob通常用byte[]表示,故携程_byte[]。(_byte对应byte类型;byte对应Byte类型。)

  <select id="selectUsersById" statementType="CALLABLE" useCache="false">
    {call select_user_by_id(
        #{id, mode=IN},
        #{userName, mode=OUT, jdbcType=VARCHAR},
        #{headImg, mode=OUT, jdbcType=BLOB, javaType=_byte[]},
        #{createTime, mode=OUT, jdbcType=TIMESTAMP}
    )}
  </select>

调用测试:

    @Test
    public void UserMapperTest(){
        SqlSession sqlSession = getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        User user = new User();
        user.setId(2L);
        System.out.println(user.getUserName());
        System.out.println(user.getHeadImg());
        System.out.println(user.getCreateTime());
        userMapper.selectUsersById(user);
        System.out.println("----------------------------------");
        System.out.println(user.getUserName());
        System.out.println(user.getHeadImg());
        System.out.println(user.getCreateTime());
    }

调试结果:

mybatis入门篇:存储过程的操作

 2、含ResultType/ResultMap查询

编写存储过程

DELIMITER $$
CREATE PROCEDURE `select _user_page`(IN _offset BIGINT, IN _limit BIGINT, OUT total BIGINT)
BEGIN
    #查询数据总数
    SELECT COUNT(*)  INTO total FROM user;
        #分页查询数据
        SELECT * FROM user LIMIT _offset, _limit;
END
$$
DELIMITER $$

编写mapper接口和xml

public interface UserMapper {
    List<User> selectUsersPage(Map<String,Integer> map);
}
  <select id="selectUsersPage" statementType="CALLABLE" useCache="false"
          resultType="com.forest.owl.entity.User">
    {call select_user_page(
        #{offset, mode=IN},
        #{limit, mode=IN},
        #{totalCount, mode=OUT, jdbcType=BIGINT, javaType=Integer}
    )}
  </select>
    @Test
    public void UserMapperTest(){
        SqlSession sqlSession = getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put();
        map.put();
        List<User> userList = userMapper.selectUsersPage(map);
        System.out.println(userList.size());
        System.out.println(map.get("totalCount"));
    }

mybatis入门篇:存储过程的操作