@Override public int executeUpdate(String query, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); queryParameters.validateParameters(); HQLQueryPlan plan = getHQLQueryPlan( query, false ); boolean success = false; int result = 0; try { result = plan.performExecuteUpdate( queryParameters, this ); success = true; } finally { afterOperation(success); } temporaryPersistenceContext.clear(); return result; }
@Override public Object load( Serializable id, Object optionalObject, SessionImplementor session, LockOptions lockOptions) { final Serializable[] batch = session.getPersistenceContext() .getBatchFetchQueue() .getEntityBatch( persister(), id, maxBatchSize, persister().getEntityMode() ); final int numberOfIds = ArrayHelper.countNonNull( batch ); if ( numberOfIds <= 1 ) { return singleKeyLoader.load( id, optionalObject, session ); } 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 ); return getObjectFromList( results, id, session ); }
private List doTheLoad(String sql, QueryParameters queryParameters, SessionImplementor 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<AfterLoadAction>(); 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.getTransactionCoordinator().getJdbcCoordinator().release( st ); } }
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; }
protected Object doBatchLoad( Serializable id, Loader loaderToUse, SessionImplementor session, Serializable[] ids, Object optionalObject, LockOptions lockOptions) { if ( log.isDebugEnabled() ) { log.debugf( "Batch loading entity: %s", MessageHelper.infoString( persister, ids, session.getFactory() ) ); } QueryParameters qp = buildQueryParameters( id, ids, optionalObject, lockOptions ); try { final List results = loaderToUse.doQueryAndInitializeNonLazyCollections( session, qp, false ); log.debug( "Done entity batch load" ); return getObjectFromList(results, id, session); } catch ( SQLException sqle ) { throw session.getFactory().getSQLExceptionHelper().convert( sqle, "could not load an entity batch: " + MessageHelper.infoString( persister(), ids, session.getFactory() ), loaderToUse.getSQLString() ); } }
@Override public ScrollableResults scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); checkTransactionSynchStatus(); if ( LOG.isTraceEnabled() ) { LOG.tracev( "Scroll SQL query: {0}", customQuery.getSQL() ); } CustomLoader loader = new CustomLoader( customQuery, getFactory() ); autoFlushIfRequired( loader.getQuerySpaces() ); dontFlushFromFind++; //stops flush being called multiple times if this method is recursively called try { return loader.scroll(queryParameters, this); } finally { delayedAfterCompletion(); dontFlushFromFind--; } }
/** * Modify the SQL, adding lock hints and comments, if necessary */ protected String preprocessSQL( String sql, QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) throws HibernateException { sql = applyLocks( sql, parameters, dialect, afterLoadActions ); // Keep this here, rather than moving to Select. Some Dialects may need the hint to be appended to the very // end or beginning of the finalized SQL statement, so wait until everything is processed. if ( parameters.getQueryHints() != null && parameters.getQueryHints().size() > 0 ) { sql = dialect.getQueryHintString( sql, parameters.getQueryHints() ); } return getFactory().getSettings().isCommentsEnabled() ? prependComment( sql, parameters ) : sql; }
protected boolean shouldUseFollowOnLocking( QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) { if ( dialect.useFollowOnLocking() ) { // currently only one lock mode is allowed in follow-on locking final LockMode lockMode = determineFollowOnLockMode( parameters.getLockOptions() ); final LockOptions lockOptions = new LockOptions( lockMode ); if ( lockOptions.getLockMode() != LockMode.UPGRADE_SKIPLOCKED ) { LOG.usingFollowOnLocking(); lockOptions.setTimeOut( parameters.getLockOptions().getTimeOut() ); lockOptions.setScope( parameters.getLockOptions().getScope() ); afterLoadActions.add( new AfterLoadAction() { @Override public void afterLoad(SessionImplementor session, Object entity, Loadable persister) { ( (Session) session ).buildLockRequest( lockOptions ).lock( persister.getEntityName(), entity ); } } ); parameters.setLockOptions( new LockOptions() ); return true; } } return false; }
public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException { verifyParameters(); before(); Map namedParams = getNamedParams(); NativeSQLQuerySpecification spec = generateQuerySpecification( namedParams ); QueryParameters qp = getQueryParameters( namedParams ); qp.setScrollMode( scrollMode ); try { return getSession().scroll( spec, qp ); } finally { after(); } }
private Object getRowFromResultSet( final ResultSet resultSet, final SessionImplementor session, final QueryParameters queryParameters, final LockMode[] lockModesArray, final EntityKey optionalObjectKey, final List hydratedObjects, final EntityKey[] keys, boolean returnProxies) throws SQLException, HibernateException { return getRowFromResultSet( resultSet, session, queryParameters, lockModesArray, optionalObjectKey, hydratedObjects, keys, returnProxies, null ); }
/** * Called by subclasses that batch initialize collections */ protected final void loadCollectionSubselect( final SessionImplementor session, final Serializable[] ids, final Object[] parameterValues, final Type[] parameterTypes, final Map<String, TypedValue> namedParameters, final Type type) throws HibernateException { Type[] idTypes = new Type[ids.length]; Arrays.fill( idTypes, type ); try { doQueryAndInitializeNonLazyCollections( session, new QueryParameters( parameterTypes, parameterValues, namedParameters, ids ), true ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, "could not load collection by subselect: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ), getSQLString() ); } }
/** * Return the query results, using the query cache, called * by subclasses that implement cacheable queries */ protected List list( final SessionImplementor session, final QueryParameters queryParameters, final Set<Serializable> querySpaces, final Type[] resultTypes) throws HibernateException { final boolean cacheable = factory.getSettings().isQueryCacheEnabled() && queryParameters.isCacheable(); if ( cacheable ) { return listUsingQueryCache( session, queryParameters, querySpaces, resultTypes ); } else { return listIgnoreQueryCache( session, queryParameters ); } }
protected void putResultInQueryCache( final SessionImplementor session, final QueryParameters queryParameters, final Type[] resultTypes, final QueryCache queryCache, final QueryKey key, final List result) { if ( session.getCacheMode().isPutEnabled() ) { boolean put = queryCache.put( key, key.getResultTransformer().getCachedResultTypes( resultTypes ), result, queryParameters.isNaturalKeyLookup(), session ); if ( put && factory.getStatistics().isStatisticsEnabled() ) { factory.getStatisticsImplementor() .queryCachePut( getQueryIdentifier(), queryCache.getRegion().getName() ); } } }
protected AbstractScrollableResults( ResultSet rs, PreparedStatement ps, SessionImplementor sess, Loader loader, QueryParameters queryParameters, Type[] types, HolderInstantiator holderInstantiator) { this.resultSet=rs; this.ps=ps; this.session = sess; this.loader = loader; this.queryParameters = queryParameters; this.types = types; this.holderInstantiator = holderInstantiator!=null && holderInstantiator.isRequired() ? holderInstantiator : null; }
@Override public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); CustomLoader loader = new CustomLoader( customQuery, getFactory() ); boolean success = false; List results; try { results = loader.list(this, queryParameters); success = true; } finally { afterOperation(success); } temporaryPersistenceContext.clear(); return results; }
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<String, int[]>(); for ( String name : queryParameters.getNamedParameters().keySet() ) { namedParameterLocMap.put( name, namedParameterContext.getNamedParameterLocations( name ) ); } return namedParameterLocMap; }
protected List executeLoad( SessionImplementor session, QueryParameters queryParameters, LoadQueryDetails loadQueryDetails, boolean returnProxies, ResultTransformer forcedResultTransformer) throws SQLException { final List<AfterLoadAction> afterLoadActions = new ArrayList<AfterLoadAction>(); return executeLoad( session, queryParameters, loadQueryDetails, returnProxies, forcedResultTransformer, afterLoadActions ); }
/** * Coordinates the efforts to perform a scroll across all the included query translators. * * @param queryParameters The query parameters * @param session The session * * @return The query result iterator * * @throws HibernateException Indicates a problem performing the query */ public ScrollableResults performScroll( QueryParameters queryParameters, SessionImplementor session) throws HibernateException { if ( TRACE_ENABLED ) { LOG.tracev( "Iterate: {0}", getSourceQuery() ); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length != 1 ) { throw new QueryException( "implicit polymorphism not supported for scroll() queries" ); } if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) { throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" ); } return translators[0].scroll( queryParameters, session ); }
/** * 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, SessionImplementor session) throws HibernateException { if ( TRACE_ENABLED ) { 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; }
@Override public int executeUpdate(String query, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); checkTransactionSynchStatus(); queryParameters.validateParameters(); HQLQueryPlan plan = getHQLQueryPlan( query, false ); autoFlushIfRequired( plan.getQuerySpaces() ); boolean success = false; int result = 0; try { result = plan.performExecuteUpdate( queryParameters, this ); success = true; } finally { afterOperation(success); delayedAfterCompletion(); } return result; }
@Override public int executeNativeUpdate(NativeSQLQuerySpecification nativeQuerySpecification, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); checkTransactionSynchStatus(); queryParameters.validateParameters(); NativeSQLQueryPlan plan = getNativeSQLQueryPlan( nativeQuerySpecification ); autoFlushIfRequired( plan.getCustomQuery().getQuerySpaces() ); boolean success = false; int result = 0; try { result = plan.performExecuteUpdate(queryParameters, this); success = true; } finally { afterOperation(success); delayedAfterCompletion(); } return result; }
@Override public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { errorIfClosed(); checkTransactionSynchStatus(); if ( LOG.isTraceEnabled() ) { LOG.tracev( "SQL query: {0}", customQuery.getSQL() ); } CustomLoader loader = new CustomLoader( customQuery, getFactory() ); autoFlushIfRequired( loader.getQuerySpaces() ); dontFlushFromFind++; boolean success = false; try { List results = loader.list(this, queryParameters); success = true; return results; } finally { dontFlushFromFind--; delayedAfterCompletion(); afterOperation(success); } }
@Override public Object load(Serializable id, Object optionalObject, SessionImplementor 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 ); } catch ( SQLException sqle ) { throw getFactory().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; }
public ScrollableResults scroll(final QueryParameters queryParameters, final SessionImplementor session) throws HibernateException { return scroll( queryParameters, resultTypes, getHolderInstantiator( queryParameters.getResultTransformer(), getReturnAliasesForTransformer() ), session ); }
/** * Append <tt>FOR UPDATE OF</tt> clause, if necessary. This * empty superclass implementation merely returns its first * argument. */ protected String applyLocks( String sql, QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) throws HibernateException { return sql; }
private String prependComment(String sql, QueryParameters parameters) { String comment = parameters.getComment(); if ( comment == null ) { return sql; } else { return new StringBuilder( comment.length() + sql.length() + 5 ) .append( "/* " ) .append( comment ) .append( " */ " ) .append( sql ) .toString(); } }
/** * Execute an SQL query and attempt to instantiate instances of the class mapped by the given * persister from each row of the <tt>ResultSet</tt>. If an object is supplied, will attempt to * initialize that object. If a collection is supplied, attempt to initialize that collection. */ public List doQueryAndInitializeNonLazyCollections( final SessionImplementor session, final QueryParameters queryParameters, final boolean returnProxies) throws HibernateException, SQLException { return doQueryAndInitializeNonLazyCollections( session, queryParameters, returnProxies, null ); }
public ScrollableResults scroll(final QueryParameters queryParameters, final SessionImplementor session) throws HibernateException { HolderInstantiator hi = HolderInstantiator.createClassicHolderInstantiator( holderConstructor, queryParameters.getResultTransformer() ); return scroll( queryParameters, returnTypes, hi, session ); }
private List doQuery( final SessionImplementor 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.getTransactionCoordinator().getJdbcCoordinator().release( st ); } }
private Map buildNamedParameterLocMap(QueryParameters queryParameters) { if ( queryParameters.getNamedParameters()!=null ) { final Map namedParameterLocMap = new HashMap(); for(String name : queryParameters.getNamedParameters().keySet()){ namedParameterLocMap.put( name, getNamedParameterLocs(name) ); } return namedParameterLocMap; } else { return null; } }
private ScrollMode getScrollMode(boolean scroll, boolean hasFirstRow, boolean useLimitOffSet, QueryParameters queryParameters) { final boolean canScroll = getFactory().getSettings().isScrollableResultSetsEnabled(); if ( canScroll ) { if ( scroll ) { return queryParameters.getScrollMode(); } if ( hasFirstRow && !useLimitOffSet ) { return ScrollMode.SCROLL_INSENSITIVE; } } return null; }
/** * Called by subclasses that load entities * @param persister only needed for logging */ protected final List loadEntity( final SessionImplementor session, final Object key, final Object index, final Type keyType, final Type indexType, final EntityPersister persister) throws HibernateException { LOG.debug( "Loading collection element by index" ); List result; try { result = doQueryAndInitializeNonLazyCollections( session, new QueryParameters( new Type[] { keyType, indexType }, new Object[] { key, index } ), false ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, "could not load collection element by index", getSQLString() ); } LOG.debug( "Done entity load" ); return result; }
/** * Called by subclasses that initialize collections */ public final void loadCollection( final SessionImplementor session, final Serializable id, final Type type) throws HibernateException { if ( LOG.isDebugEnabled() ) LOG.debugf( "Loading collection: %s", MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ) ); Serializable[] ids = new Serializable[]{id}; try { doQueryAndInitializeNonLazyCollections( session, new QueryParameters( new Type[]{type}, ids, ids ), true ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, "could not initialize a collection: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ), getSQLString() ); } LOG.debug( "Done loading collection" ); }
/** * Called by wrappers that batch initialize collections */ public final void loadCollectionBatch( final SessionImplementor session, final Serializable[] ids, final Type type) throws HibernateException { if ( LOG.isDebugEnabled() ) LOG.debugf( "Batch loading collection: %s", MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ) ); Type[] idTypes = new Type[ids.length]; Arrays.fill( idTypes, type ); try { doQueryAndInitializeNonLazyCollections( session, new QueryParameters( idTypes, ids, ids ), true ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, "could not initialize a collection batch: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ), getSQLString() ); } LOG.debug( "Done batch load" ); }
/** * Return the query results, as an instance of <tt>ScrollableResults</tt> */ @Override public ScrollableResults scroll(QueryParameters queryParameters, SessionImplementor session) throws HibernateException { // Delegate to the QueryLoader... errorIfDML(); return queryLoader.scroll( queryParameters, session ); }
private QueryKey generateQueryKey( SessionImplementor session, QueryParameters queryParameters) { return QueryKey.generateQueryKey( getSQLString(), queryParameters, FilterKey.createFilterKeys( session.getLoadQueryInfluencers().getEnabledFilters() ), session, createCacheableResultTransformer( queryParameters ) ); }
private CacheableResultTransformer createCacheableResultTransformer(QueryParameters queryParameters) { return CacheableResultTransformer.create( queryParameters.getResultTransformer(), getResultRowAliases(), includeInResultRow() ); }
private List doList(final SessionImplementor session, final QueryParameters queryParameters, final ResultTransformer forcedResultTransformer) throws HibernateException { final boolean stats = getFactory().getStatistics().isStatisticsEnabled(); long startTime = 0; if ( stats ) startTime = System.nanoTime(); List result; try { result = doQueryAndInitializeNonLazyCollections( session, queryParameters, true, forcedResultTransformer ); } catch ( SQLException sqle ) { throw factory.getSQLExceptionHelper().convert( sqle, "could not execute query", getSQLString() ); } if ( stats ) { final long endTime = System.nanoTime(); final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS ); getFactory().getStatisticsImplementor().queryExecuted( getQueryIdentifier(), result.size(), milliseconds ); } return result; }
@Override public void initialize(Serializable id, SessionImplementor session) throws HibernateException { if ( log.isDebugEnabled() ) { log.debugf( "Loading collection: %s", MessageHelper.collectionInfoString( collectionPersister, id, getFactory() ) ); } final Serializable[] ids = new Serializable[]{id}; try { final QueryParameters qp = new QueryParameters(); qp.setPositionalParameterTypes( new Type[]{ collectionPersister.getKeyType() } ); qp.setPositionalParameterValues( ids ); qp.setCollectionKeys( ids ); executeLoad( session, qp, staticLoadQuery, true, null ); } catch ( SQLException sqle ) { throw getFactory().getSQLExceptionHelper().convert( sqle, "could not initialize a collection: " + MessageHelper.collectionInfoString( collectionPersister, id, getFactory() ), staticLoadQuery.getSqlStatement() ); } log.debug( "Done loading collection" ); }
public ScrollableResults scroll( final QueryParameters queryParameters, final SessionImplementor session) throws HibernateException { checkQuery( queryParameters ); return scroll( queryParameters, queryReturnTypes, buildHolderInstantiator( queryParameters.getResultTransformer() ), session ); }