Spring、Mybatis、Mysql 通过存储过程实现分页--Mybatis实现

Mybatis的分页功能可不可以通过数据库中的存储过程动态执行查询来帮助实现?

Spring、Mybatis、Mysql 通过存储过程实现分页博客一共有3部分
第一部分:存储过程动态分页之存储过程实现
第二部分:存储过程动态分页之Mybatis实现
第三部分:存储过程动态分页之实际工程demo

目前这篇讲的是
第二部分:存储过程动态分页之Mybatis实现


Mybatis通过调用dynamic_paging存储过程来实现对任意查询的分页


Mybatis是可以调用存储过程的。例如,在Mybatis的mapper文件中:



<select id="get***" resultMap="**Map"
		parameterMap="procMap" statementType="CALLABLE">
        CALL proc(?,?)
</select>
<parameterMap type="java.util.Map" id="procMap">
		<parameter property="param1" mode="IN" jdbcType="INTEGER" />
		<parameter property="param1" mode="IN" jdbcType="INTEGER" />
	</parameterMap>


分页的存储过程

CREATE PROCEDURE `dynamic_paging`(sql varchar(500),page_begin int,size int)


问题就在于dynamic_paging该存储过程第一个参数(sql)是需要在调用前动态生成。
例如:

select * from tableA,tableB where tableA.id=tableB.uid and id=10 



Mybatis 调用时的sql为:


select * from tableA,tableB where tableA.id=tableB.uid and id= ?


id=10这个是由程序传入的。是一个具体的业务数据。

而这部分又是调用dynamic_paging的第一个参数。

具体的解决方法为:MyBatis Velocity,链接 http://www.mybatis.org/velocity-scripting/index.html



在配置文件中动态填充业务逻辑值,然后传给存储过程


例如:

<select id="get***"  resultMap="***Map"
		parameterMap="procMap" statementType="CALLABLE" lang="velocity" >

		#set( $sql = 'select * from tableA,tableB where tableA.id=tableB.uid and id='+$_parameter.id ) 
		#set( $begin=$_parameter.pageBegin)
		#set( $size=$_parameter.fetchSize)
		CALL dynamic_paging(@{sql},@{begin},@{size})
</select>

<parameterMap type="java.util.Map" id="procMap">
                <parameter property="id" />
		<parameter property="pageBegin" />
		<parameter property="fetchSize"/>
</parameterMap>





猜你喜欢

转载自xkorey.iteye.com/blog/2367212