All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gu.sql2java.PageQueryLimitOffsetImpl Maven / Gradle / Ivy

There is a newer version: 5.2.0
Show newest version
package gu.sql2java;

import static com.google.common.base.Strings.isNullOrEmpty;
import static gu.sql2java.parser.ParserSupport.parseSelectUnchecked;

import gu.sql2java.pagehelper.Page;
import gu.sql2java.pagehelper.PageHelper;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.statement.select.Limit;
import net.sf.jsqlparser.statement.select.Offset;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

class PageQueryLimitOffsetImpl implements IPageQueryWrap {

	public PageQueryLimitOffsetImpl() {
	}

	@Override
	public String wrap(String sql, int startRow, int numRows) {
		Select select;
		if(!isNullOrEmpty(sql) && null != (select = parseSelectUnchecked(sql))){
			/**
			 * 提供startRow,numRows的情况下优先使用startRow,numRows
			 * 没有提供startRow,numRows的情况下,检查是否PageHelper是否启动,
			 * 如果启动,则使用PageHelper提供的参数来计算分页查询的起始偏移(offset)和记录数量(row_count)
			 */
			boolean rebuild = true;
			if(startRow == 1 && numRows < 0){
				@SuppressWarnings("rawtypes")
				Page page;
				if(null != (page = PageHelper.getLocalPage()) && page.isEnable()){
					startRow = (page.getPageNum() - 1 ) * page.getPageSize();
					numRows = page.getPageSize();
				}else{
					rebuild = false;
				}
			}else {
				startRow --;
			}
			if(rebuild){
				PlainSelect plainSelect = (PlainSelect)select.getSelectBody();
				if(numRows > 0){
					Limit limit = new Limit();
					limit.setRowCount(new LongValue(numRows));
					plainSelect.setLimit(limit);
				}
				if(startRow >= 0){
					Offset offset = new Offset();
//					offset.setOffset(startRow);
					// update for jsqlparser 4.5
					offset.setOffset(new LongValue(startRow));
					plainSelect.setOffset(offset);
				}
				return select.toString();
			}
		}
		return null;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy