001/*
002 * Copyright 2006-2012 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.item.database.support;
018
019import java.util.Map;
020
021import org.springframework.batch.item.database.Order;
022
023/**
024 * Oracle implementation of a
025 * {@link org.springframework.batch.item.database.PagingQueryProvider} using
026 * database specific features.
027 * 
028 * @author Thomas Risberg
029 * @author Michael Minella
030 * @since 2.0
031 */
032public class OraclePagingQueryProvider extends AbstractSqlPagingQueryProvider {
033
034        @Override
035        public String generateFirstPageQuery(int pageSize) {
036                return SqlPagingQueryUtils.generateRowNumSqlQuery(this, false, buildRowNumClause(pageSize));
037        }
038
039        @Override
040        public String generateRemainingPagesQuery(int pageSize) {
041                return SqlPagingQueryUtils.generateRowNumSqlQuery(this, true, buildRowNumClause(pageSize));
042        }
043
044        @Override
045        public String generateJumpToItemQuery(int itemIndex, int pageSize) {
046                int page = itemIndex / pageSize;
047                int offset = (page * pageSize);
048                offset = offset == 0 ? 1 : offset;
049                String sortKeySelect = this.getSortKeySelect();
050                return SqlPagingQueryUtils.generateRowNumSqlQueryWithNesting(this, sortKeySelect, sortKeySelect, false, "TMP_ROW_NUM = "
051                                + offset);
052        }
053        
054        private String getSortKeySelect() {
055                StringBuilder sql = new StringBuilder();
056                String prefix = "";
057                
058                for (Map.Entry<String, Order> sortKey : this.getSortKeys().entrySet()) {
059                        sql.append(prefix);
060                        prefix = ", ";
061                        sql.append(sortKey.getKey());
062                }
063                
064                return sql.toString();
065        }
066
067        private String buildRowNumClause(int pageSize) {
068                return new StringBuilder().append("ROWNUM <= ").append(pageSize).toString();
069        }
070
071}