Package org.hibernate.engine.spi

Examples of org.hibernate.engine.spi.SessionImplementor


  public static interface LazyInitializationWork<T> {
    public T doWork();
  }

  private <T> T withTemporarySessionIfNeeded(LazyInitializationWork<T> lazyInitializationWork) {
    SessionImplementor originalSession = null;
    boolean isTempSession = false;
    boolean isJTA = false;

    if ( session == null ) {
      if ( specjLazyLoad ) {
View Full Code Here


    Object processCollection(Object collection, CollectionType collectionType)
  throws HibernateException {

    if ( collection!=null && (collection instanceof PersistentCollection) ) {

      final SessionImplementor session = getSession();
      PersistentCollection coll = (PersistentCollection) collection;
      if ( coll.setCurrentSession(session) ) {
        reattachCollection( coll, collectionType );
      }
      return null;
View Full Code Here

  }

  final Object processArrayOrNewCollection(Object collection, CollectionType collectionType)
  throws HibernateException {

    final SessionImplementor session = getSession();

    if (collection==null) {
      //do nothing
      return null;
    }
    else {
      CollectionPersister persister = session.getFactory().getCollectionPersister( collectionType.getRole() );

      final PersistenceContext persistenceContext = session.getPersistenceContext();
      //TODO: move into collection type, so we can use polymorphism!
      if ( collectionType.hasHolder() ) {

        if (collection==CollectionType.UNFETCHED_COLLECTION) return null;
View Full Code Here

   *
   * @param event The create event to be handled.
   * @throws HibernateException
   */
  public void onPersist(PersistEvent event, Map createCache) throws HibernateException {
    final SessionImplementor source = event.getSession();
    final Object object = event.getObject();

    final Object entity;
    if ( object instanceof HibernateProxy ) {
      LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer();
      if ( li.isUninitialized() ) {
        if ( li.getSession() == source ) {
          return; //NOTE EARLY EXIT!
        }
        else {
          throw new PersistentObjectException( "uninitialized proxy passed to persist()" );
        }
      }
      entity = li.getImplementation();
    }
    else {
      entity = object;
    }

    final String entityName;
    if ( event.getEntityName() != null ) {
      entityName = event.getEntityName();
    }
    else {
      entityName = source.bestGuessEntityName( entity );
      event.setEntityName( entityName );
    }

    final EntityEntry entityEntry = source.getPersistenceContext().getEntry( entity );
    EntityState entityState = getEntityState( entity, entityName, entityEntry, source );
    if ( entityState == EntityState.DETACHED ) {
      // JPA 2, in its version of a "foreign generated", allows the id attribute value
      // to be manually set by the user, even though this manual value is irrelevant.
      // The issue is that this causes problems with the Hibernate unsaved-value strategy
      // which comes into play here in determining detached/transient state.
      //
      // Detect if we have this situation and if so null out the id value and calculate the
      // entity state again.

      // NOTE: entityEntry must be null to get here, so we cannot use any of its values
      EntityPersister persister = source.getFactory().getEntityPersister( entityName );
      if ( ForeignGenerator.class.isInstance( persister.getIdentifierGenerator() ) ) {
        if ( LOG.isDebugEnabled() && persister.getIdentifier( entity, source ) != null ) {
          LOG.debug( "Resetting entity id attribute to null for foreign generator" );
        }
        persister.setIdentifier( entity, null, source );
View Full Code Here

   */
  public void onInitializeCollection(InitializeCollectionEvent event)
  throws HibernateException {

    PersistentCollection collection = event.getCollection();
    SessionImplementor source = event.getSession();

    CollectionEntry ce = source.getPersistenceContext().getCollectionEntry(collection);
    if (ce==null) throw new HibernateException("collection was evicted");
    if ( !collection.wasInitialized() ) {
      final boolean traceEnabled = LOG.isTraceEnabled();
      if ( traceEnabled ) {
        LOG.tracev( "Initializing collection {0}",
            MessageHelper.collectionInfoString( ce.getLoadedPersister(), collection, ce.getLoadedKey(), source ) );
        LOG.trace( "Checking second-level cache" );
      }

      final boolean foundInCache = initializeCollectionFromCache(
          ce.getLoadedKey(),
          ce.getLoadedPersister(),
          collection,
          source
        );

      if ( foundInCache ) {
        if ( traceEnabled ) {
          LOG.trace( "Collection initialized from cache" );
        }
      }
      else {
        if ( traceEnabled ) {
          LOG.trace( "Collection not cached" );
        }
        ce.getLoadedPersister().initialize( ce.getLoadedKey(), source );
        if ( traceEnabled ) {
          LOG.trace( "Collection initialized" );
        }

        if ( source.getFactory().getStatistics().isStatisticsEnabled() ) {
          source.getFactory().getStatisticsImplementor().fetchCollection(
              ce.getLoadedPersister().getRole()
            );
        }
      }
    }
View Full Code Here

   * Handle the given update event.
   *
   * @param event The update event to be handled.
   */
  public void onSaveOrUpdate(SaveOrUpdateEvent event) {
    final SessionImplementor source = event.getSession();
    final Object object = event.getObject();
    final Serializable requestedId = event.getRequestedId();

    if ( requestedId != null ) {
      //assign the requested id to the proxy, *before*
      //reassociating the proxy
      if ( object instanceof HibernateProxy ) {
        ( ( HibernateProxy ) object ).getHibernateLazyInitializer().setIdentifier( requestedId );
      }
    }

    // For an uninitialized proxy, noop, don't even need to return an id, since it is never a save()
    if ( reassociateIfUninitializedProxy( object, source ) ) {
      LOG.trace( "Reassociated uninitialized proxy" );
    }
    else {
      //initialize properties of the event:
      final Object entity = source.getPersistenceContext().unproxyAndReassociate( object );
      event.setEntity( entity );
      event.setEntry( source.getPersistenceContext().getEntry( entity ) );
      //return the id in the event object
      event.setResultId( performSaveOrUpdate( event ) );
    }

  }
View Full Code Here

  Object processCollection(Object collection, CollectionType type)
    throws HibernateException {

    if (collection!=null) {

      SessionImplementor session = getSession();

      final PersistentCollection persistentCollection;
      if ( type.isArrayType() ) {
         persistentCollection = session.getPersistenceContext().getCollectionHolder(collection);
        // if no array holder we found an unwrappered array (this can't occur,
        // because we now always call wrap() before getting to here)
        // return (ah==null) ? true : searchForDirtyCollections(ah, type);
      }
      else {
View Full Code Here

   * complete.
   *
   * @param persister The persister for which to complete loading.
   */
  public void endLoadingCollections(CollectionPersister persister) {
    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 matches = null;
    Iterator iter = localLoadingCollectionKeys.iterator();
    while ( iter.hasNext() ) {
      final CollectionKey collectionKey = (CollectionKey) iter.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();
        }
        matches.add( lce );
        if ( lce.getCollection().getOwner() == null ) {
          session.getPersistenceContext().addUnownedCollection(
              new CollectionKey(
                  persister,
                  lce.getKey(),
                  persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode()
              ),
View Full Code Here

    if ( debugEnabled ) LOG.debugf( "%s collections initialized for role: %s", count, persister.getRole() );
  }

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

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

    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() );
    }

    boolean addToCache = hasNoQueuedAdds && // there were no queued additions
        persister.hasCache() &&             // and the role has a cache
        session.getCacheMode().isPutEnabled() &&
        !ce.isDoremove();                   // and this is not a forced initialization during flush
    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).
      return; // EARLY EXIT!!!!!
    }

    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 ) {
          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

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.