org.hibernate.engine.spi.QueryParameters Java Examples

The following examples show how to use org.hibernate.engine.spi.QueryParameters. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HQLQueryPlan.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Coordinates the efforts to perform an execution across all the included query translators.
 *
 * @param queryParameters The query parameters
 * @param session The session
 *
 * @return The aggregated "affected row" count
 *
 * @throws HibernateException Indicates a problem performing the execution
 */
public int performExecuteUpdate(QueryParameters queryParameters, SharedSessionContractImplementor session)
		throws HibernateException {
	if ( traceEnabled ) {
		LOG.tracev( "Execute update: {0}", getSourceQuery() );
		queryParameters.traceParameters( session.getFactory() );
	}
	if ( translators.length != 1 ) {
		LOG.splitQueries( getSourceQuery(), translators.length );
	}
	int result = 0;
	for ( QueryTranslator translator : translators ) {
		result += translator.executeUpdate( queryParameters, session );
	}
	return result;
}
 
Example #2
Source File: Loader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ScrollMode getScrollMode(
		boolean scroll,
		boolean hasFirstRow,
		boolean useLimitOffSet,
		QueryParameters queryParameters) {
	final boolean canScroll = getFactory().getSessionFactoryOptions().isScrollableResultSetsEnabled();
	if ( canScroll ) {
		if ( scroll ) {
			return queryParameters.getScrollMode();
		}
		if ( hasFirstRow && !useLimitOffSet ) {
			return ScrollMode.SCROLL_INSENSITIVE;
		}
	}
	return null;
}
 
Example #3
Source File: ResultSetProcessorHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static Map<String, int[]> buildNamedParameterLocMap(
		QueryParameters queryParameters,
		NamedParameterContext namedParameterContext) {
	if ( queryParameters.getNamedParameters() == null || queryParameters.getNamedParameters().isEmpty() ) {
		return null;
	}

	final Map<String, int[]> namedParameterLocMap = new HashMap<>();
	for ( String name : queryParameters.getNamedParameters().keySet() ) {
		namedParameterLocMap.put(
				name,
				namedParameterContext.getNamedParameterLocations( name )
		);
	}
	return namedParameterLocMap;
}
 
Example #4
Source File: CustomLoader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected int bindParameterValues(
		PreparedStatement statement,
		QueryParameters queryParameters,
		int startIndex,
		SharedSessionContractImplementor session) throws SQLException {
	final Serializable optionalId = queryParameters.getOptionalId();
	if ( optionalId != null ) {
		paramValueBinders.get( 0 ).bind( statement, queryParameters, session, startIndex );
		return session.getFactory().getMetamodel()
				.entityPersister( queryParameters.getOptionalEntityName() )
				.getIdentifierType()
				.getColumnSpan( session.getFactory() );
	}

	int span = 0;
	for ( ParameterBinder paramValueBinder : paramValueBinders ) {
		span += paramValueBinder.bind(
				statement,
				queryParameters,
				session,
				startIndex + span
		);
	}
	return span;
}
 
Example #5
Source File: StatelessSessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int executeNativeUpdate(
		NativeSQLQuerySpecification nativeSQLQuerySpecification,
		QueryParameters queryParameters) throws HibernateException {
	checkOpen();
	queryParameters.validateParameters();
	NativeSQLQueryPlan plan = getNativeQueryPlan( nativeSQLQuerySpecification );

	boolean success = false;
	int result = 0;
	try {
		result = plan.performExecuteUpdate( queryParameters, this );
		success = true;
	}
	finally {
		afterOperation( success );
	}
	temporaryPersistenceContext.clear();
	return result;
}
 
Example #6
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public List listFilter(Object collection, String filter, QueryParameters queryParameters) {
	checkOpenOrWaitingForAutoClose();
	checkTransactionSynchStatus();
	FilterQueryPlan plan = getFilterQueryPlan( collection, filter, queryParameters, false );
	List results = Collections.EMPTY_LIST;

	boolean success = false;
	dontFlushFromFind++;   //stops flush being called multiple times if this method is recursively called
	try {
		results = plan.performList( queryParameters, this );
		success = true;
	}
	finally {
		dontFlushFromFind--;
		afterOperation( success );
		delayedAfterCompletion();
	}
	return results;
}
 
Example #7
Source File: BatchingEntityLoader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected QueryParameters buildQueryParameters(
		Serializable id,
		Serializable[] ids,
		Object optionalObject,
		LockOptions lockOptions) {
	Type[] types = new Type[ids.length];
	Arrays.fill( types, persister().getIdentifierType() );

	QueryParameters qp = new QueryParameters();
	qp.setPositionalParameterTypes( types );
	qp.setPositionalParameterValues( ids );
	qp.setOptionalObject( optionalObject );
	qp.setOptionalEntityName( persister().getEntityName() );
	qp.setOptionalId( id );
	qp.setLockOptions( lockOptions );
	return qp;
}
 
Example #8
Source File: ReactiveSubselectOneToManyLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ReactiveSubselectOneToManyLoader(
		QueryableCollection persister,
		String subquery,
		Collection entityKeys,
		QueryParameters queryParameters,
		Map<String, int[]> namedParameterLocMap,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	super( persister, 1, subquery, factory, loadQueryInfluencers );

	keys = new Serializable[ entityKeys.size() ];
	Iterator iter = entityKeys.iterator();
	int i=0;
	while ( iter.hasNext() ) {
		keys[i++] = ( (EntityKey) iter.next() ).getIdentifier();
	}

	this.namedParameters = queryParameters.getNamedParameters();
	this.types = queryParameters.getFilteredPositionalParameterTypes();
	this.values = queryParameters.getFilteredPositionalParameterValues();
	this.namedParameterLocMap = namedParameterLocMap;
}
 
Example #9
Source File: StatelessSessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int executeUpdate(String query, QueryParameters queryParameters) throws HibernateException {
	checkOpen();
	queryParameters.validateParameters();
	HQLQueryPlan plan = getQueryPlan( query, false );
	boolean success = false;
	int result = 0;
	try {
		result = plan.performExecuteUpdate( queryParameters, this );
		success = true;
	}
	finally {
		afterOperation( success );
	}
	temporaryPersistenceContext.clear();
	return result;
}
 
Example #10
Source File: Loader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static EntityKey getOptionalObjectKey(QueryParameters queryParameters, SharedSessionContractImplementor session) {
	final Object optionalObject = queryParameters.getOptionalObject();
	final Serializable optionalId = queryParameters.getOptionalId();
	final String optionalEntityName = queryParameters.getOptionalEntityName();

	if ( optionalObject != null && optionalEntityName != null ) {
		return session.generateEntityKey(
				optionalId, session.getEntityPersister(
						optionalEntityName,
						optionalObject
				)
		);
	}
	else {
		return null;
	}

}
 
Example #11
Source File: ReactiveQueryTranslatorImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
public CompletionStage<Integer> executeReactiveUpdate(QueryParameters queryParameters, ReactiveSession session) {
	errorIfSelect();

	// Multiple UPDATE SQL strings are not supported yet
	String sql = getSqlStatements()[0];

	Object[] parameterValues = toParameterArray(
			queryParameters,
			getCollectedParameterSpecifications( session ),
			session.getSharedContract()
	);
	return CompletionStages.completedFuture(0).thenCompose(
			count -> session.getReactiveConnection()
					.update( sql, parameterValues )
					.thenApply( updateCount -> count + updateCount )
	);
}
 
Example #12
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public CompletionStage<Integer> executeReactiveUpdate(NativeSQLQuerySpecification specification,
													  QueryParameters parameters) {
	checkOpenOrWaitingForAutoClose();
	pulseTransactionCoordinator();
	parameters.validateParameters();

	ReactiveNativeSQLQueryPlan reactivePlan = //getNativeQueryPlan( specification );
			new ReactiveNativeSQLQueryPlan(
					specification.getQueryString(),
					new SQLCustomQuery(
							specification.getQueryString(),
							specification.getQueryReturns(),
							specification.getQuerySpaces(),
							getFactory()
					) );
	return reactiveAutoFlushIfRequired( reactivePlan.getCustomQuery().getQuerySpaces() )
			.thenCompose( v -> reactivePlan.performExecuteReactiveUpdate( parameters, this ) )
			.whenComplete( (count, x) -> {
				afterOperation( x == null );
				delayedAfterCompletion();
			} );
}
 
Example #13
Source File: ReactiveHQLQueryPlan.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void needsLimitLoop(QueryParameters queryParameters, List<Object> combinedResults, IdentitySet distinction, AtomicInteger includedCount, List<Object> tmpList) {
	// NOTE : firstRow is zero-based
	final int first = queryParameters.getRowSelection().getFirstRow() == null ? 0 : queryParameters.getRowSelection().getFirstRow();
	final int max = queryParameters.getRowSelection().getMaxRows() == null ? -1 : queryParameters.getRowSelection().getMaxRows();
	for ( final Object result : tmpList ) {
		if ( !distinction.add( result ) ) {
			continue;
		}
		int included = includedCount.addAndGet( 1 );
		if ( included < first ) {
			continue;
		}
		combinedResults.add( result );
		if ( max >= 0 && included > max ) {
			return;
		}
	}
}
 
Example #14
Source File: ReactiveHQLQueryPlan.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
public CompletionStage<Integer> performExecuteReactiveUpdate(QueryParameters queryParameters, ReactiveSession session) {
	if ( log.isTraceEnabled() ) {
		log.tracev( "Execute update: {0}", getSourceQuery() );
		queryParameters.traceParameters( session.getFactory() );
	}
	QueryTranslator[] translators = getTranslators();
	if ( translators.length != 1 ) {
		log.splitQueries( getSourceQuery(), translators.length );
	}

	CompletionStage<Integer> combinedStage = CompletionStages.completedFuture(0);
	for ( QueryTranslator translator : translators ) {
		ReactiveQueryTranslatorImpl reactiveTranslator = (ReactiveQueryTranslatorImpl) translator;
		combinedStage = combinedStage
				.thenCompose(
						count -> reactiveTranslator.executeReactiveUpdate( queryParameters, session )
								.thenApply( updateCount -> count + updateCount )
				);
	}
	return combinedStage;
}
 
Example #15
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private CompletionStage<List<Object>> listReactiveCustomQuery(CustomQuery customQuery, QueryParameters parameters) {
		checkOpenOrWaitingForAutoClose();
//		checkTransactionSynchStatus();

		ReactiveCustomLoader loader = new ReactiveCustomLoader( customQuery, getFactory() );

//		autoFlushIfRequired( loader.getQuerySpaces() );

//		dontFlushFromFind++;
//		boolean success = false;
			return loader.reactiveList( this, parameters )
					.whenComplete( (r, e) -> delayedAfterCompletion() );
//			success = true;
//			dontFlushFromFind--;
//			afterOperation( success );
	}
 
Example #16
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
	public <T> CompletionStage<List<T>> reactiveList(String query, QueryParameters parameters) throws HibernateException {
		checkOpenOrWaitingForAutoClose();
		pulseTransactionCoordinator();
		parameters.validateParameters();

		HQLQueryPlan plan = parameters.getQueryPlan();
		if ( plan == null ) {
			plan = getQueryPlan( query, false );
		}
		ReactiveHQLQueryPlan reactivePlan = (ReactiveHQLQueryPlan) plan;

		return reactiveAutoFlushIfRequired( plan.getQuerySpaces() )
				// FIXME: I guess I can fix this as a separate issue
//				dontFlushFromFind++;   //stops flush being called multiple times if this method is recursively called
				.thenCompose( v -> reactivePlan.performReactiveList(parameters, this ) )
				.whenComplete( (list, x) -> {
//					dontFlushFromFind--;
					afterOperation( x == null );
					delayedAfterCompletion();
				} )
				//TODO: this typecast is rubbish
				.thenApply( list -> (List<T>) list );
	}
 
Example #17
Source File: StatelessSessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ScrollableResultsImplementor scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
		throws HibernateException {
	checkOpen();
	CustomLoader loader = new CustomLoader( customQuery, getFactory() );
	return loader.scroll( queryParameters, this );
}
 
Example #18
Source File: QueryTranslatorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected int bindParameterValues(
		PreparedStatement statement,
		QueryParameters queryParameters,
		int startIndex,
		SharedSessionContractImplementor session) throws SQLException {

	int span = 0;
	for ( ParameterBinder binder : paramValueBinders ) {
		span += binder.bind( statement, queryParameters, session, startIndex + span );
	}
	return span;
}
 
Example #19
Source File: ReactiveLoaderBasedLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
List<Object> getRowsFromResultSet(
final ResultSet rs,
final QueryParameters queryParameters,
final SharedSessionContractImplementor session,
final boolean returnProxies,
final ResultTransformer forcedResultTransformer,
final int maxRows,
final List<Object> hydratedObjects,
final List<EntityKey[]> subselectResultKeys) throws SQLException;
 
Example #20
Source File: DynamicBatchingEntityLoaderBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object load(
		Serializable id,
		Object optionalObject,
		SharedSessionContractImplementor session,
		LockOptions lockOptions) {
	final Serializable[] batch = session.getPersistenceContext()
			.getBatchFetchQueue()
			.getEntityBatch( persister(), id, maxBatchSize, persister().getEntityMode() );

	final int numberOfIds = ArrayHelper.countNonNull( batch );
	if ( numberOfIds <= 1 ) {
		final Object result =  singleKeyLoader.load( id, optionalObject, session );
		if ( result == null ) {
			// There was no entity with the specified ID. Make sure the EntityKey does not remain
			// in the batch to avoid including it in future batches that get executed.
			BatchFetchQueueHelper.removeBatchLoadableEntityKey( id, persister(), session );
		}
		return result;
	}

	final Serializable[] idsToLoad = new Serializable[numberOfIds];
	System.arraycopy( batch, 0, idsToLoad, 0, numberOfIds );

	if ( log.isDebugEnabled() ) {
		log.debugf( "Batch loading entity: %s", MessageHelper.infoString( persister(), idsToLoad, session.getFactory() ) );
	}

	QueryParameters qp = buildQueryParameters( id, idsToLoad, optionalObject, lockOptions );
	List results = dynamicLoader.doEntityBatchFetch( session, qp, idsToLoad );

	// The EntityKey for any entity that is not found will remain in the batch.
	// Explicitly remove the EntityKeys for entities that were not found to
	// avoid including them in future batches that get executed.
	BatchFetchQueueHelper.removeNotFoundBatchLoadableEntityKeys( idsToLoad, results, persister(), session );

	return getObjectFromList( results, id, session );
}
 
Example #21
Source File: NamedParameterSpecification.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Bind the appropriate value into the given statement at the specified position.
 *
 * @param statement The statement into which the value should be bound.
 * @param qp The defined values for the current query execution.
 * @param session The session against which the current execution is occuring.
 * @param position The position from which to start binding value(s).
 *
 * @return The number of sql bind positions "eaten" by this bind operation.
 */
@Override
public int bind(
		PreparedStatement statement,
		QueryParameters qp,
		SharedSessionContractImplementor session,
		int position) throws SQLException {
	TypedValue typedValue = qp.getNamedParameters().get( name );
	typedValue.getType().nullSafeSet( statement, typedValue.getValue(), position, session );
	return typedValue.getType().getColumnSpan( session.getFactory() );
}
 
Example #22
Source File: PositionalParamBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int bind(
		PreparedStatement statement,
		QueryParameters qp,
		SharedSessionContractImplementor session,
		int position) throws SQLException {
	final TypedValue typedValue = qp.getNamedParameters().get( Integer.toString( label ) );
	typedValue.getType().nullSafeSet( statement, typedValue.getValue(), position, session );
	return typedValue.getType().getColumnSpan( session.getFactory() );
}
 
Example #23
Source File: ParameterBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static int bindNamedParameters(
		final PreparedStatement ps,
		final QueryParameters queryParameters,
		final int start,
		final NamedParameterSource source,
		final SessionImplementor session) throws SQLException, HibernateException {
	return bindNamedParameters( ps, queryParameters.getNamedParameters(), start, source, session );
}
 
Example #24
Source File: ReactiveQueryTranslatorImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @deprecated Use {@link #list(SharedSessionContractImplementor, QueryParameters)} instead.
 */
@Deprecated
@Override
public List<Object> list(SharedSessionContractImplementor session, QueryParameters queryParameters)
		throws HibernateException {
	throw new UnsupportedOperationException("Use #reactiveList instead");
}
 
Example #25
Source File: AbstractLoadPlanBasedEntityLoader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object load(Serializable id, Object optionalObject, SharedSessionContractImplementor session, LockOptions lockOptions) {

	final Object result;
	try {
		final QueryParameters qp = new QueryParameters();
		qp.setPositionalParameterTypes( new Type[] { entityPersister.getIdentifierType() } );
		qp.setPositionalParameterValues( new Object[] { id } );
		qp.setOptionalObject( optionalObject );
		qp.setOptionalEntityName( entityPersister.getEntityName() );
		qp.setOptionalId( id );
		qp.setLockOptions( lockOptions );

		final List results = executeLoad(
				session,
				qp,
				staticLoadQuery,
				false,
				null
		);
		result = extractEntityResult( results, id );
	}
	catch ( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert(
				sqle,
				"could not load an entity: " + MessageHelper.infoString(
						entityPersister,
						id,
						entityPersister.getIdentifierType(),
						getFactory()
				),
				staticLoadQuery.getSqlStatement()
		);
	}

	log.debugf( "Done entity load : %s#%s", getEntityName(), id );
	return result;
}
 
Example #26
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public CompletionStage<Integer> executeReactiveUpdate(String query, QueryParameters parameters) {
	checkOpenOrWaitingForAutoClose();
	pulseTransactionCoordinator();
	parameters.validateParameters();

	ReactiveHQLQueryPlan reactivePlan = getQueryPlan( query, false );
	return reactiveAutoFlushIfRequired( reactivePlan.getQuerySpaces() )
			.thenAccept( v -> verifyImmutableEntityUpdate( reactivePlan ) )
			.thenCompose( v -> reactivePlan.performExecuteReactiveUpdate( parameters, this ) )
			.whenComplete( (count, x) -> {
				afterOperation( x == null );
				delayedAfterCompletion();
			} );
}
 
Example #27
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters) {
	checkOpenOrWaitingForAutoClose();
	checkTransactionSynchStatus();
	FilterQueryPlan plan = getFilterQueryPlan( collection, filter, queryParameters, true );
	Iterator itr = plan.performIterate( queryParameters, this );
	delayedAfterCompletion();
	return itr;
}
 
Example #28
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public List doQueryAndInitializeNonLazyCollections(
		final SharedSessionContractImplementor session,
		final QueryParameters queryParameters,
		final boolean returnProxies,
		final ResultTransformer forcedResultTransformer)
		throws HibernateException, SQLException {
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
	if ( queryParameters.isReadOnlyInitialized() ) {
		// The read-only/modifiable mode for the query was explicitly set.
		// Temporarily set the default read-only/modifiable setting to the query's setting.
		persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
	}
	else {
		// The read-only/modifiable setting for the query was not initialized.
		// Use the default read-only/modifiable from the persistence context instead.
		queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
	}
	persistenceContext.beforeLoad();
	List result;
	try {
		try {
			result = doQuery( session, queryParameters, returnProxies, forcedResultTransformer );
		}
		finally {
			persistenceContext.afterLoad();
		}
		persistenceContext.initializeNonLazyCollections();
	}
	finally {
		// Restore the original default
		persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
	}
	return result;
}
 
Example #29
Source File: AbstractProducedQuery.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected ScrollableResultsImplementor doScroll(ScrollMode scrollMode) {
	if (getMaxResults() == 0){
		return EmptyScrollableResults.INSTANCE;
	}
	final String query = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() );
	QueryParameters queryParameters = makeQueryParametersForExecution( query );
	queryParameters.setScrollMode( scrollMode );
	return getProducer().scroll( query, queryParameters );
}
 
Example #30
Source File: CustomLoader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected String applyLocks(
		String sql,
		QueryParameters parameters,
		Dialect dialect,
		List<AfterLoadAction> afterLoadActions) throws QueryException {
	final LockOptions lockOptions = parameters.getLockOptions();
	if ( lockOptions == null ||
			( lockOptions.getLockMode() == LockMode.NONE && lockOptions.getAliasLockCount() == 0 ) ) {
		return sql;
	}

	// user is request locking, lets see if we can apply locking directly to the SQL...

	// 		some dialects wont allow locking with paging...
	afterLoadActions.add(
			new AfterLoadAction() {
				private final LockOptions originalLockOptions = lockOptions.makeCopy();

				@Override
				public void afterLoad(SharedSessionContractImplementor session, Object entity, Loadable persister) {
					( (Session) session ).buildLockRequest( originalLockOptions ).lock(
							persister.getEntityName(),
							entity
					);
				}
			}
	);
	parameters.getLockOptions().setLockMode( LockMode.READ );

	return sql;
}