Spring, Mybatis, Mysql realize paging through stored procedures--stored procedure implementation

Can the paging function of Mybatis help to implement the query dynamically through the stored procedure in the database?

Spring, Mybatis, Mysql realizes paging through stored procedures. There are three parts to the blog.
The first part: the stored procedure implementation
of stored procedure dynamic paging. The second part: the Mybatis implementation of stored procedure dynamic paging. The third part: the
actual project demo of stored procedure dynamic paging.

This article is about the
first



part: the implementation of stored procedures for dynamic paging of stored procedures. With this idea, I will practice it, and I feel that it is possible at first.


SQL can be executed dynamically in Mysql. For example:


CREATE PROCEDURE `dynamic_sql`(sql varchar(500))
BEGIN
PREPARE stmt FROM sql;
EXECUTE stmt;
END


call the stored procedure

CALL dynamic_sql('select * from table');


It can correctly return the result of SQL execution.

Database stored procedures can dynamically execute SQL, and Mybatis only needs to be responsible for calling the paging stored procedures.

The part that requires additional processing is: prohibiting dynamic SQL from performing operations that modify data.

The specific implementation method is to filter strings that Mysql modifies data, such as: update, delete, etc.


Initial implementation of dynamic_paging, the code is


CREATE PROCEDURE `dynamic_paging`(sql varchar(500),page_begin int,size int)
BEGIN
set @lowercase:=lower(sql);
if(!LOCATE('call',@lowercase) && !LOCATE('delete',@lowercase) && !LOCATE('drop',@lowercase) && !LOCATE('truncate',@lowercase) && !LOCATE('update',@lowercase) && !LOCATE('delete',@lowercase) && !LOCATE('alter',@lowercase) )then
set @temp:='';
if(LOCATE('select',@lowercase))then
set @temp:=concat(@lowercase,' limit ',page_begin,',',page_end);
PREPARE stmt FROM @temp;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end if;
end if;
END




Parameter and logic description:
Parameter:
sql: paging statement
page_begin, size of dynamic query: 2 parameters of limit (limit page_begin, size)
Logic:
After converting the paging statement to lowercase, do the modification data keyword filter, and then paginate A limit operation is added at the end of the statement.



call the stored procedure

CALL dynamic_sql('select * from tableA',0,10);
##or
CALL dynamic_sql('select * from tableA,tableB where tableA.id=tableB.uid',0,10);
##or
CALL dynamic_sql('select * from tableA order by id desc',0,10);



So far, the database part of the work has come to an end.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326527926&siteId=291194637