---
title: "Hibernate oracle 分页 三层分页原理"
author: "taoshi"
date: "2015-01-28T10:47:10Z"
tags: []
categories: ["数据库"]
slug: "hibernate-oracle"
draft: false
lastmod: "2015-01-28T10:47:10Z"
id: 2180709
url: "https://taoshi.iteye.com/blog/2180709"
---

用习惯的hibernate 更加的忽略底层，现在连数据库怎么分页都记住不了。

oracle 三层分页原理

	StringBuffer pagingSelect = new StringBuffer( sql.length()+100 );
		if (hasOffset) {
			pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
		}
		else {
			pagingSelect.append("select * from ( ");
		}
		<u>pagingSelect.append(sql);</u>
		if (hasOffset) {
			pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
		}
		else {
			pagingSelect.append(" ) where rownum <= ?");
		}
查询21 - 40 条记录
1.pagingSelect.append(sql); 这段内容是我们自己的业务语句
2.pagingSelect.append(" ) row_ where rownum <= ? 查找到40条以内记录
3.>?查询到大于21条记录

这种查询在绝大多数拥有较高的查询效率，由于CBO优化器 基于成本的优化器为了提高SQL语句的执行效率，会把外层的条件拿到内部去执行，这样二层rownum<40 的记录如果不满足就直接返回