Package org.hibernate.engine.spi

Examples of org.hibernate.engine.spi.SessionImplementor


      if (logger.isDebugEnabled()) {
        logger.debug("First-level parse tree for " + namedQuery.name() + ":");
        parser.showAst(hqlAst, System.out);
      }

      SessionImplementor hibernateSession = em.unwrap(SessionImplementor.class);
      ASTQueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
      query = (QueryTranslatorImpl) translatorFactory.createQueryTranslator(
              namedQuery.name(), jpaQuery, java.util.Collections.EMPTY_MAP, hibernateSession.getFactory());

      query.compile(Collections.EMPTY_MAP, false);

      if (query.getReturnTypes().length != 1) {
        throw new RuntimeException(
View Full Code Here


      return createNamedNativeQuery( (NamedSQLQueryDefinition) queryDefinition, resultType );
    }
  }

  protected <T> TypedQuery<T> createNamedJpqlQuery(NamedQueryDefinition namedQueryDefinition, Class<T> resultType) {
    SessionImplementor session = (SessionImplementor) getDelegate();
    final org.hibernate.Query query = session.createQuery( namedQueryDefinition );
    if ( resultType != null ) {
      resultClassChecking( resultType, query );
    }

    return wrapAsJpaQuery( namedQueryDefinition, query );
View Full Code Here

  /*
   *  Copied from org.hibernate.jpa.spi.AbstractEntityManagerImpl
   */
  private void resultClassChecking(Class resultClass, org.hibernate.Query hqlQuery) {
    // make sure the query is a select -> HHH-7192
    final SessionImplementor session = unwrap( SessionImplementor.class );
    final HQLQueryPlan queryPlan = session.getFactory().getQueryPlanCache()
        .getHQLQueryPlan( hqlQuery.getQueryString(), false, session.getLoadQueryInfluencers().getEnabledFilters() );
    if ( queryPlan.getTranslators()[0].isManipulationStatement() ) {
      throw new IllegalArgumentException( "Update/delete queries cannot be typed" );
    }

    // do some return type validation checking
View Full Code Here

      if (logger.isDebugEnabled()) {
        logger.debug("First-level parse tree for " + namedQuery.name() + ":");
        parser.showAst(hqlAst, System.out);
      }

      SessionImplementor hibernateSession = em.unwrap(SessionImplementor.class);
      ASTQueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
      query = (QueryTranslatorImpl) translatorFactory.createQueryTranslator(
              namedQuery.name(), jpaQuery, java.util.Collections.EMPTY_MAP, hibernateSession.getFactory());

      query.compile(Collections.EMPTY_MAP, false);

      if (query.getReturnTypes().length != 1) {
        throw new RuntimeException(
View Full Code Here

        throw new LazyInitializationException( "could not initialize proxy - no Session" );
      }
      try {
        SessionFactoryImplementor sf = (SessionFactoryImplementor)
            SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
        SessionImplementor session = (SessionImplementor) sf.openSession();
       
        // TODO: On the next major release, add an
        // 'isJTA' or 'getTransactionFactory' method to Session.
        boolean isJTA = session.getTransactionCoordinator()
            .getTransactionContext().getTransactionEnvironment()
            .getTransactionFactory()
            .compatibleWithJtaSynchronization();
       
        if ( !isJTA ) {
          // Explicitly handle the transactions only if we're not in
          // a JTA environment.  A lazy loading temporary session can
          // be created even if a current session and transaction are
          // open (ex: session.clear() was used).  We must prevent
          // multiple transactions.
          ( ( Session) session ).beginTransaction();
        }

        try {
          target = session.immediateLoad( entityName, id );
        }
        finally {
          // make sure the just opened temp session gets closed!
          try {
            if ( !isJTA ) {
              ( ( Session) session ).getTransaction().commit();
            }
            ( (Session) session ).close();
          }
          catch (Exception e) {
            log.warn( "Unable to close temporary session used to load lazy proxy associated to no session" );
          }
        }
        initialized = true;
        checkTargetState();
      }
      catch (Exception e) {
        e.printStackTrace();
        throw new LazyInitializationException( e.getMessage() );
      }
    }
    else if ( session.isOpen() && session.isConnected() ) {
      target = session.immediateLoad( entityName, id );
      initialized = true;
      checkTargetState();
    }
    else {
      throw new LazyInitializationException( "could not initialize proxy - Session was closed or disced" );
View Full Code Here

   * complete.
   *
   * @param persister The persister for which to complete loading.
   */
  public void endLoadingCollections(CollectionPersister persister) {
    final SessionImplementor session = getLoadContext().getPersistenceContext().getSession();
    if ( !loadContexts.hasLoadingCollectionEntries()
        && localLoadingCollectionKeys.isEmpty() ) {
      return;
    }

    // in an effort to avoid concurrent-modification-exceptions (from
    // potential recursive calls back through here as a result of the
    // eventual call to PersistentCollection#endRead), we scan the
    // internal loadingCollections map for matches and store those matches
    // in a temp collection.  the temp collection is then used to "drive"
    // the #endRead processing.
    List<LoadingCollectionEntry> matches = null;
    final Iterator itr = localLoadingCollectionKeys.iterator();
    while ( itr.hasNext() ) {
      final CollectionKey collectionKey = (CollectionKey) itr.next();
      final LoadingCollectionEntry lce = loadContexts.locateLoadingCollectionEntry( collectionKey );
      if ( lce == null ) {
        LOG.loadingCollectionKeyNotFound( collectionKey );
      }
      else if ( lce.getResultSet() == resultSet && lce.getPersister() == persister ) {
        if ( matches == null ) {
          matches = new ArrayList<LoadingCollectionEntry>();
        }
        matches.add( lce );
        if ( lce.getCollection().getOwner() == null ) {
          session.getPersistenceContext().addUnownedCollection(
              new CollectionKey(
                  persister,
                  lce.getKey(),
                  persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode()
              ),
View Full Code Here

    }
  }

  private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) {
    LOG.tracev( "Ending loading collection [{0}]", lce );
    final SessionImplementor session = getLoadContext().getPersistenceContext().getSession();

    // warning: can cause a recursive calls! (proxy initialization)
    final boolean hasNoQueuedAdds = lce.getCollection().endRead();

    if ( persister.getCollectionType().hasHolder() ) {
      getLoadContext().getPersistenceContext().addCollectionHolder( lce.getCollection() );
    }

    CollectionEntry ce = getLoadContext().getPersistenceContext().getCollectionEntry( lce.getCollection() );
    if ( ce == null ) {
      ce = getLoadContext().getPersistenceContext().addInitializedCollection( persister, lce.getCollection(), lce.getKey() );
    }
    else {
      ce.postInitialize( lce.getCollection() );
//      if (ce.getLoadedPersister().getBatchSize() > 1) { // not the best place for doing this, moved into ce.postInitialize
//        getLoadContext().getPersistenceContext().getBatchFetchQueue().removeBatchLoadableCollection(ce);
//      }
    }


    // add to cache if:
    boolean addToCache =
        // there were no queued additions
        hasNoQueuedAdds
        // and the role has a cache
        && persister.hasCache()
        // and this is not a forced initialization during flush
        && session.getCacheMode().isPutEnabled() && !ce.isDoremove();
    if ( addToCache ) {
      addCollectionToCache( lce, persister );
    }

    if ( LOG.isDebugEnabled() ) {
      LOG.debugf(
          "Collection fully initialized: %s",
          MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session )
      );
    }
    if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
      session.getFactory().getStatisticsImplementor().loadCollection( persister.getRole() );
    }
  }
View Full Code Here

   *
   * @param lce The entry representing the collection to add
   * @param persister The persister
   */
  private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) {
    final SessionImplementor session = getLoadContext().getPersistenceContext().getSession();
    final SessionFactoryImplementor factory = session.getFactory();

    final boolean debugEnabled = LOG.isDebugEnabled();
    if ( debugEnabled ) {
      LOG.debugf( "Caching collection: %s", MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) );
    }

    if ( !session.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( session ) ) {
      // some filters affecting the collection are enabled on the session, so do not do the put into the cache.
      if ( debugEnabled ) {
        LOG.debug( "Refusing to add to cache due to enabled filters" );
      }
      // todo : add the notion of enabled filters to the CacheKey to differentiate filtered collections from non-filtered;
      //      but CacheKey is currently used for both collections and entities; would ideally need to define two seperate ones;
      //      currently this works in conjuction with the check on
      //      DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from
      //      cache with enabled filters).
      // EARLY EXIT!!!!!
      return;
    }

    final Object version;
    if ( persister.isVersioned() ) {
      Object collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner( lce.getKey(), persister );
      if ( collectionOwner == null ) {
        // generally speaking this would be caused by the collection key being defined by a property-ref, thus
        // the collection key and the owner key would not match up.  In this case, try to use the key of the
        // owner instance associated with the collection itself, if one.  If the collection does already know
        // about its owner, that owner should be the same instance as associated with the PC, but we do the
        // resolution against the PC anyway just to be safe since the lookup should not be costly.
        if ( lce.getCollection() != null ) {
          final Object linkedOwner = lce.getCollection().getOwner();
          if ( linkedOwner != null ) {
            final Serializable ownerKey = persister.getOwnerEntityPersister().getIdentifier( linkedOwner, session );
            collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner( ownerKey, persister );
          }
        }
        if ( collectionOwner == null ) {
          throw new HibernateException(
              "Unable to resolve owner of loading collection [" +
                  MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) +
                  "] for second level caching"
          );
        }
      }
      version = getLoadContext().getPersistenceContext().getEntry( collectionOwner ).getVersion();
    }
    else {
      version = null;
    }

    final CollectionCacheEntry entry = new CollectionCacheEntry( lce.getCollection(), persister );
    final CacheKey cacheKey = session.generateCacheKey( lce.getKey(), persister.getKeyType(), persister.getRole() );

    try {
      session.getEventListenerManager().cachePutStart();
      final boolean put = persister.getCacheAccessStrategy().putFromLoad(
          cacheKey,
          persister.getCacheEntryStructure().structure( entry ),
          session.getTimestamp(),
          version,
          factory.getSettings().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH
      );

      if ( put && factory.getStatistics().isStatisticsEnabled() ) {
        factory.getStatisticsImplementor().secondLevelCachePut( persister.getCacheAccessStrategy().getRegion().getName() );
      }
    }
    finally {
      session.getEventListenerManager().cachePutEnd();
    }
  }
View Full Code Here

    return INVOKE_IMPLEMENTATION;

  }

  private Object getReplacement() {
    final SessionImplementor session = getSession();
    if ( isUninitialized() && session != null && session.isOpen()) {
      final EntityKey key = session.generateEntityKey(
          getIdentifier(),
          session.getFactory().getEntityPersister( getEntityName() )
      );
      final Object entity = session.getPersistenceContext().getEntity(key);
      if (entity!=null) setImplementation( entity );
    }

    if ( isUninitialized() ) {
      if (replacement==null) {
View Full Code Here

    }
  }

  protected void resultClassChecking(Class resultClass, org.hibernate.Query hqlQuery) {
    // make sure the query is a select -> HHH-7192
    final SessionImplementor session = unwrap( SessionImplementor.class );
    final HQLQueryPlan queryPlan = session.getFactory().getQueryPlanCache().getHQLQueryPlan(
        hqlQuery.getQueryString(),
        false,
        session.getLoadQueryInfluencers().getEnabledFilters()
    );
    if ( queryPlan.getTranslators()[0].isManipulationStatement() ) {
      throw new IllegalArgumentException( "Update/delete queries cannot be typed" );
    }
View Full Code Here

TOP

Related Classes of org.hibernate.engine.spi.SessionImplementor

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.