1. MySQL创建存储过程
完成分页查询功能,同时返回参数记录总条数信息:
DELIMITER // CREATE PROCEDURE sp_article_page( IN pageIndex BIGINT, IN pageSize BIGINT, IN te_id BIGINT, IN grade_id INT, IN subject_id BIGINT, OUT total_count BIGINT ) BEGIN -- set @subjectId = subject_id; -- 可能为null SET @sql = 'SELECT * FROM tb_article '; SET @sqlWhere = CONCAT(' WHERE article_author = ', te_id); -- 教师 -- 大纲 IF (grade_id IS NOT NULL) OR (subject_id IS NOT NULL) THEN SET @sqlWhere = CONCAT(@sqlWhere, ' and outline_id in (select o_id from tb_outline where 1=1 '); IF grade_id IS NOT NULL THEN SET @sqlWhere = CONCAT(@sqlWhere, ' and grade_id=', grade_id); END IF; IF subject_id IS NOT NULL THEN SET @sqlWhere = CONCAT(@sqlWhere, ' and subject_id=', subject_id); END IF; SET @sqlWhere = CONCAT(@sqlWhere,')'); END IF; -- 计算总页数 SET @sqlCount = CONCAT('SELECT count(*) into @c FROM tb_article ',@sqlWhere); PREPARE s FROM @sqlCount; EXECUTE s; -- deallocate s; -- set @pageCount int default 0; IF (@c MOD pageSize) = 0 THEN SET @pageCount = (@c DIV pageSize); ELSE SET @pageCount = (@c DIV pageSize + 1); END IF; IF pageIndex > @pageCount THEN SET pageIndex = @pageCount; END IF; IF pageIndex<1 THEN SET pageIndex = 1; END IF; -- 计算skip SET @skip = (pageIndex-1)*pageSize; SET @sql = CONCAT(@sql, @sqlWhere, ' limit ', @skip, ',',pageSize); PREPARE stmp FROM @sql; EXECUTE stmp; SET total_count = FOUND_ROWS(); END
SQL调用存储过程:
CALL sp_article_page(1, 5,1,NULL,NULL, @c); SELECT @c;
2. MyBatis调用存储过程【注解方式】
out参数返回给page对象的属性:page.totalCount;
public interface ArticleManageDao { @Select("call sp_article_page(#{page.pageIndex}, #{page.pageSize},#{te_id},#{grade_id},#{subject_id}, #{page.totalCount, mode=OUT,jdbcType=BIGINT});") @Options(statementType = StatementType.CALLABLE) List<Article> selectPage(@Param("page") Page page, @Param("te_id") Long te_id,@Param("grade_id") Integer grade_id,@Param("subject_id") Long subject_id); }
end