下面列出了org.hibernate.engine.spi.RowSelection#getMaxRows ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List doTheLoad(String sql, QueryParameters queryParameters, SharedSessionContractImplementor session) throws SQLException {
final RowSelection selection = queryParameters.getRowSelection();
final int maxRows = LimitHelper.hasMaxRows( selection ) ?
selection.getMaxRows() :
Integer.MAX_VALUE;
final List<AfterLoadAction> afterLoadActions = new ArrayList<>();
final SqlStatementWrapper wrapper = executeQueryStatement( sql, queryParameters, false, afterLoadActions, session );
final ResultSet rs = wrapper.getResultSet();
final Statement st = wrapper.getStatement();
try {
return processResultSet( rs, queryParameters, session, false, null, maxRows, afterLoadActions );
}
finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution();
}
}
private void doTheLoad(String sql, QueryParameters queryParameters, SharedSessionContractImplementor session) throws SQLException {
final RowSelection selection = queryParameters.getRowSelection();
final int maxRows = LimitHelper.hasMaxRows( selection ) ?
selection.getMaxRows() :
Integer.MAX_VALUE;
final List<AfterLoadAction> afterLoadActions = Collections.emptyList();
final SqlStatementWrapper wrapper = executeQueryStatement( sql, queryParameters, false, afterLoadActions, session );
final ResultSet rs = wrapper.getResultSet();
final Statement st = wrapper.getStatement();
try {
processResultSet( rs, queryParameters, session, true, null, maxRows, afterLoadActions );
}
finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution();
}
}
@Override
public String processSql(String sql, RowSelection selection) {
if ( selection.getMaxRows() == null ) {
return sql;
}
int top = getMaxOrLimit( selection );
if ( top == Integer.MAX_VALUE ) {
return sql;
}
Matcher selectDistinctMatcher = SELECT_DISTINCT_PATTERN.matcher( sql );
if ( selectDistinctMatcher.matches() ) {
return insertTop( selectDistinctMatcher, sql, top );
}
Matcher selectMatcher = SELECT_PATTERN.matcher( sql );
if ( selectMatcher.matches() ) {
return insertTop( selectMatcher, sql, top );
}
return sql;
}
private List doQuery(
final SharedSessionContractImplementor session,
final QueryParameters queryParameters,
final boolean returnProxies,
final ResultTransformer forcedResultTransformer) throws SQLException, HibernateException {
final RowSelection selection = queryParameters.getRowSelection();
final int maxRows = LimitHelper.hasMaxRows( selection ) ?
selection.getMaxRows() :
Integer.MAX_VALUE;
final List<AfterLoadAction> afterLoadActions = new ArrayList<AfterLoadAction>();
final SqlStatementWrapper wrapper = executeQueryStatement( queryParameters, false, afterLoadActions, session );
final ResultSet rs = wrapper.getResultSet();
final Statement st = wrapper.getStatement();
// would be great to move all this below here into another method that could also be used
// from the new scrolling stuff.
//
// Would need to change the way the max-row stuff is handled (i.e. behind an interface) so
// that I could do the control breaking at the means to know when to stop
try {
return processResultSet(
rs,
queryParameters,
session,
returnProxies,
forcedResultTransformer,
maxRows,
afterLoadActions
);
}
finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution();
}
}
/**
* If we're able to guess a likely size of the results we can optimize allocation
* of our datastructures.
* Essentially if we detect the user is not using pagination, we attempt to use the FetchSize
* as a reasonable hint. If fetch size is not being set either, it is reasonable to expect
* that we're going to have a single hit. In such a case it would be tempting to return a constant
* of value one, but that's dangerous as it doesn't scale up appropriately for example
* with an ArrayList if the guess is wrong.
*
* @param rowSelection
* @return a reasonable size to use for allocation
*/
@SuppressWarnings("UnnecessaryUnboxing")
private int guessResultSize(RowSelection rowSelection) {
if ( rowSelection != null ) {
final int maxReasonableAllocation = rowSelection.getFetchSize() != null ? rowSelection.getFetchSize().intValue() : 100;
if ( rowSelection.getMaxRows() != null && rowSelection.getMaxRows().intValue() > 0 ) {
return Math.min( maxReasonableAllocation, rowSelection.getMaxRows().intValue() );
}
else if ( rowSelection.getFetchSize() != null && rowSelection.getFetchSize().intValue() > 0 ) {
return rowSelection.getFetchSize().intValue();
}
}
return 7;//magic number guessed as a reasonable default.
}
/**
* Some dialect-specific LIMIT clauses require the maximum last row number
* (aka, first_row_number + total_row_count), while others require the maximum
* returned row count (the total maximum number of rows to return).
*
* @param selection the selection criteria for rows.
*
* @return The appropriate value to bind into the limit clause.
*/
protected final int getMaxOrLimit(RowSelection selection) {
final int firstRow = convertToFirstRowValue( LimitHelper.getFirstRow( selection ) );
final int lastRow = selection.getMaxRows();
final int maxRows = useMaxForLimit() ? lastRow + firstRow : lastRow;
// Use Integer.MAX_VALUE on overflow
if ( maxRows < 0 ) {
return Integer.MAX_VALUE;
}
else {
return maxRows;
}
}
@Override
public void setMaxRows(RowSelection selection, PreparedStatement statement) throws SQLException {
if ( LimitHelper.hasMaxRows( selection ) ) {
int maxRows = selection.getMaxRows() + convertToFirstRowValue( LimitHelper.getFirstRow( selection ) );
// Use Integer.MAX_VALUE on overflow
if ( maxRows < 0 ) {
statement.setMaxRows( Integer.MAX_VALUE );
}
else {
statement.setMaxRows( maxRows );
}
}
}
@Override
public List extractResults(
ResultSet resultSet,
final SharedSessionContractImplementor session,
QueryParameters queryParameters,
NamedParameterContext namedParameterContext,
boolean returnProxies,
boolean readOnly,
ResultTransformer forcedResultTransformer,
List<AfterLoadAction> afterLoadActionList) throws SQLException {
handlePotentiallyEmptyCollectionRootReturns( loadPlan, queryParameters.getCollectionKeys(), resultSet, session );
final int maxRows;
final RowSelection selection = queryParameters.getRowSelection();
if ( LimitHelper.hasMaxRows( selection ) ) {
maxRows = selection.getMaxRows();
LOG.tracef( "Limiting ResultSet processing to just %s rows", maxRows );
}
else {
maxRows = Integer.MAX_VALUE;
}
// Handles the "FETCH ALL PROPERTIES" directive in HQL
final boolean forceFetchLazyAttributes = false;
final ResultSetProcessingContextImpl context = new ResultSetProcessingContextImpl(
resultSet,
session,
loadPlan,
aliasResolutionContext,
readOnly,
shouldUseOptionalEntityInstance,
forceFetchLazyAttributes,
returnProxies,
queryParameters,
namedParameterContext,
hadSubselectFetches
);
final List loadResults = new ArrayList();
LOG.trace( "Processing result set" );
int count;
for ( count = 0; count < maxRows && resultSet.next(); count++ ) {
LOG.debugf( "Starting ResultSet row #%s", count );
Object logicalRow = rowReader.readRow( resultSet, context );
// todo : apply transformers here?
loadResults.add( logicalRow );
context.finishUpRow();
}
LOG.tracev( "Done processing result set ({0} rows)", count );
rowReader.finishUp( context, afterLoadActionList );
context.wrapUp();
session.getPersistenceContext().initializeNonLazyCollections();
return loadResults;
}
/**
* Generates a QueryKey.
*
* @param queryString The sql query string.
* @param queryParameters The query parameters
* @param filterKeys The keys of any enabled filters.
* @param session The current session.
* @param customTransformer The result transformer; should be null if data is not transformed before being cached.
*
* @return The generate query cache key.
*/
public static QueryKey generateQueryKey(
String queryString,
QueryParameters queryParameters,
Set filterKeys,
SharedSessionContractImplementor session,
CacheableResultTransformer customTransformer) {
// disassemble positional parameters
final int positionalParameterCount = queryParameters.getPositionalParameterTypes().length;
final Type[] types = new Type[positionalParameterCount];
final Object[] values = new Object[positionalParameterCount];
for ( int i = 0; i < positionalParameterCount; i++ ) {
types[i] = queryParameters.getPositionalParameterTypes()[i];
values[i] = types[i].disassemble( queryParameters.getPositionalParameterValues()[i], session, null );
}
// disassemble named parameters
final Map<String,TypedValue> namedParameters;
if ( queryParameters.getNamedParameters() == null ) {
namedParameters = null;
}
else {
namedParameters = CollectionHelper.mapOfSize( queryParameters.getNamedParameters().size() );
for ( Map.Entry<String,TypedValue> namedParameterEntry : queryParameters.getNamedParameters().entrySet() ) {
namedParameters.put(
namedParameterEntry.getKey(),
new TypedValue(
namedParameterEntry.getValue().getType(),
namedParameterEntry.getValue().getType().disassemble(
namedParameterEntry.getValue().getValue(),
session,
null
)
)
);
}
}
// decode row selection...
final RowSelection selection = queryParameters.getRowSelection();
final Integer firstRow;
final Integer maxRows;
if ( selection != null ) {
firstRow = selection.getFirstRow();
maxRows = selection.getMaxRows();
}
else {
firstRow = null;
maxRows = null;
}
return new QueryKey(
queryString,
types,
values,
namedParameters,
firstRow,
maxRows,
filterKeys,
session.getTenantIdentifier(),
customTransformer
);
}
/**
* Is a max row limit indicated?
*
* @param selection The row selection options
*
* @return Whether a max row limit was indicated
*/
public static boolean hasMaxRows(RowSelection selection) {
return selection != null && selection.getMaxRows() != null && selection.getMaxRows() > 0;
}