Package org.hibernate.engine.spi

Examples of org.hibernate.engine.spi.PersistenceContext


      final Object id = mappedIdentifierType.instantiate( entityMode );
      final Object[] propertyValues = virtualIdComponent.getPropertyValues( entity, entityMode );
      final Type[] subTypes = virtualIdComponent.getSubtypes();
      final Type[] copierSubTypes = mappedIdentifierType.getSubtypes();
      final Iterable<PersistEventListener> persistEventListeners = persistEventListeners( session );
      final PersistenceContext persistenceContext = session.getPersistenceContext();
      final int length = subTypes.length;
      for ( int i = 0 ; i < length; i++ ) {
        if ( propertyValues[i] == null ) {
          throw new HibernateException( "No part of a composite identifier may be null" );
        }
        //JPA 2 @MapsId + @IdClass points to the pk of the entity
        if ( subTypes[i].isAssociationType() && ! copierSubTypes[i].isAssociationType() ) {
          // we need a session to handle this use case
          if ( session == null ) {
            throw new AssertionError(
                "Deprecated version of getIdentifier (no session) was used but session was required"
            );
          }
          final Object subId;
          if ( HibernateProxy.class.isInstance( propertyValues[i] ) ) {
            subId = ( (HibernateProxy) propertyValues[i] ).getHibernateLazyInitializer().getIdentifier();
          }
          else {
            EntityEntry pcEntry = session.getPersistenceContext().getEntry( propertyValues[i] );
            if ( pcEntry != null ) {
              subId = pcEntry.getId();
            }
            else {
              LOG.debug( "Performing implicit derived identity cascade" );
              final PersistEvent event = new PersistEvent( null, propertyValues[i], (EventSource) session );
              for ( PersistEventListener listener : persistEventListeners ) {
                listener.onPersist( event );
              }
              pcEntry = persistenceContext.getEntry( propertyValues[i] );
              if ( pcEntry == null || pcEntry.getId() == null ) {
                throw new HibernateException( "Unable to process implicit derived identity cascade" );
              }
              else {
                subId = pcEntry.getId();
View Full Code Here


    @Override
    public void setIdentifier(Object entity, Serializable id, EntityMode entityMode, SessionImplementor session) {
      final Object[] extractedValues = mappedIdentifierType.getPropertyValues( id, entityMode );
      final Object[] injectionValues = new Object[ extractedValues.length ];
      final PersistenceContext persistenceContext = session.getPersistenceContext();
      for ( int i = 0; i < virtualIdComponent.getSubtypes().length; i++ ) {
        final Type virtualPropertyType = virtualIdComponent.getSubtypes()[i];
        final Type idClassPropertyType = mappedIdentifierType.getSubtypes()[i];
        if ( virtualPropertyType.isEntityType() && ! idClassPropertyType.isEntityType() ) {
          if ( session == null ) {
            throw new AssertionError(
                "Deprecated version of getIdentifier (no session) was used but session was required"
            );
          }
          final String associatedEntityName = ( (EntityType) virtualPropertyType ).getAssociatedEntityName();
          final EntityKey entityKey = session.generateEntityKey(
              (Serializable) extractedValues[i],
              session.getFactory().getEntityPersister( associatedEntityName )
          );
          // it is conceivable there is a proxy, so check that first
          Object association = persistenceContext.getProxy( entityKey );
          if ( association == null ) {
            // otherwise look for an initialized version
            association = persistenceContext.getEntity( entityKey );
          }
          injectionValues[i] = association;
        }
        else {
          injectionValues[i] = extractedValues[i];
View Full Code Here

        getIdentifierOrUniqueKeyType( factory ),
        persister.getEntityMode(),
        session.getFactory()
    );

    final PersistenceContext persistenceContext = session.getPersistenceContext();
    Object result = persistenceContext.getEntity( euk );
    if ( result == null ) {
      result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
    }
    return result == null ? null : persistenceContext.proxyFor( result );
  }
View Full Code Here

    LOG.trace( "Flushing session" );

    EventSource session = event.getSession();

    final PersistenceContext persistenceContext = session.getPersistenceContext();
    session.getInterceptor().preFlush( new LazyIterator( persistenceContext.getEntitiesByKey() ) );

    prepareEntityFlushes( session, persistenceContext );
    // we could move this inside if we wanted to
    // tolerate collection initializations during
    // collection dirty checking:
    prepareCollectionFlushes( persistenceContext );
    // now, any collections that are initialized
    // inside this block do not get updated - they
    // are ignored until the next flush

    persistenceContext.setFlushing( true );
    try {
      int entityCount = flushEntities( event, persistenceContext );
      int collectionCount = flushCollections( session, persistenceContext );

      event.setNumberOfEntitiesProcessed( entityCount );
      event.setNumberOfCollectionsProcessed( collectionCount );
    }
    finally {
      persistenceContext.setFlushing(false);
    }

    //some statistics
    logFlushResults( event );
  }
View Full Code Here

  private void logFlushResults(FlushEvent event) {
    if ( !LOG.isDebugEnabled() ) {
      return;
    }
    final EventSource session = event.getSession();
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    LOG.debugf(
        "Flushed: %s insertions, %s updates, %s deletions to %s objects",
        session.getActionQueue().numberOfInsertions(),
        session.getActionQueue().numberOfUpdates(),
        session.getActionQueue().numberOfDeletions(),
        persistenceContext.getNumberOfManagedEntities()
    );
    LOG.debugf(
        "Flushed: %s (re)creations, %s updates, %s removals to %s collections",
        session.getActionQueue().numberOfCollectionCreations(),
        session.getActionQueue().numberOfCollectionUpdates(),
        session.getActionQueue().numberOfCollectionRemovals(),
        persistenceContext.getCollectionEntries().size()
    );
    new EntityPrinter( session.getFactory() ).toString(
        persistenceContext.getEntitiesByKey().entrySet()
    );
  }
View Full Code Here

   */
  protected void postFlush(SessionImplementor session) throws HibernateException {

    LOG.trace( "Post flush" );

    final PersistenceContext persistenceContext = session.getPersistenceContext();
    persistenceContext.getCollectionsByKey().clear();
   
    // the database has changed now, so the subselect results need to be invalidated
    // the batch fetching queues should also be cleared - especially the collection batch fetching one
    persistenceContext.getBatchFetchQueue().clear();

    for ( Map.Entry<PersistentCollection, CollectionEntry> me : IdentityMap.concurrentEntries( persistenceContext.getCollectionEntries() ) ) {
      CollectionEntry collectionEntry = me.getValue();
      PersistentCollection persistentCollection = me.getKey();
      collectionEntry.postFlush(persistentCollection);
      if ( collectionEntry.getLoadedPersister() == null ) {
        //if the collection is dereferenced, remove from the session cache
        //iter.remove(); //does not work, since the entrySet is not backed by the set
        persistenceContext.getCollectionEntries()
            .remove(persistentCollection);
      }
      else {
        //otherwise recreate the mapping between the collection and its key
        CollectionKey collectionKey = new CollectionKey(
            collectionEntry.getLoadedPersister(),
            collectionEntry.getLoadedKey()
        );
        persistenceContext.getCollectionsByKey().put(collectionKey, persistentCollection);
      }
    }

  }
View Full Code Here

    if ( object == null ) {
      throw new NullPointerException( "null passed to Session.evict()" );
    }

    final EventSource source = event.getSession();
    final PersistenceContext persistenceContext = source.getPersistenceContext();

    if ( object instanceof HibernateProxy ) {
      final LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer();
      final Serializable id = li.getIdentifier();
      if ( id == null ) {
        throw new IllegalArgumentException( "Could not determine identifier of proxy passed to evict()" );
      }

      final EntityPersister persister = source.getFactory().getEntityPersister( li.getEntityName() );
      final EntityKey key = source.generateEntityKey( id, persister );
      persistenceContext.removeProxy( key );

      if ( !li.isUninitialized() ) {
        final Object entity = persistenceContext.removeEntity( key );
        if ( entity != null ) {
          EntityEntry e = persistenceContext.removeEntry( entity );
          doEvict( entity, key, e.getPersister(), event.getSession() );
        }
      }
      li.unsetSession();
    }
    else {
      EntityEntry e = persistenceContext.removeEntry( object );
      if ( e != null ) {
        persistenceContext.removeEntity( e.getEntityKey() );
        doEvict( object, e.getEntityKey(), e.getPersister(), source );
      }
      else {
        // see if the passed object is even an entity, and if not throw an exception
        //     this is different than legacy Hibernate behavior, but what JPA 2.1 is calling for
        //    with EntityManager.detach
        EntityPersister persister = null;
        final String entityName = persistenceContext.getSession().guessEntityName( object );
        if ( entityName != null ) {
          try {
            persister = persistenceContext.getSession().getFactory().getEntityPersister( entityName );
          }
          catch (Exception ignore) {
          }
        }
        if ( persister == null ) {
View Full Code Here

   
    //postDelete:
    // After actually deleting a row, record the fact that the instance no longer
    // exists on the database (needed for identity-column key generation), and
    // remove it from the session cache
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    EntityEntry entry = persistenceContext.removeEntry( instance );
    if ( entry == null ) {
      throw new AssertionFailure( "possible nonthreadsafe access to session" );
    }
    entry.postDelete();

    persistenceContext.removeEntity( entry.getEntityKey() );
    persistenceContext.removeProxy( entry.getEntityKey() );
   
    if ( persister.hasCache() ) {
      persister.getCacheAccessStrategy().remove( ck );
    }
View Full Code Here

      return false;
    }

    CollectionCacheEntry cacheEntry = (CollectionCacheEntry)persister.getCacheEntryStructure().destructure(ce, factory);

    final PersistenceContext persistenceContext = source.getPersistenceContext();
        cacheEntry.assemble(collection, persister, persistenceContext.getCollectionOwner(id, persister));
        persistenceContext.getCollectionEntry(collection).postInitialize(collection);
        // addInitializedCollection(collection, persister, id);
        return true;
  }
View Full Code Here

      final PreLoadEvent preLoadEvent,
      final PostLoadEvent postLoadEvent) throws HibernateException {

    //TODO: Should this be an InitializeEntityEventListener??? (watch out for performance!)

    final PersistenceContext persistenceContext = session.getPersistenceContext();
    EntityEntry entityEntry = persistenceContext.getEntry(entity);
    if ( entityEntry == null ) {
      throw new AssertionFailure( "possible non-threadsafe access to the session" );
    }
    EntityPersister persister = entityEntry.getPersister();
    Serializable id = entityEntry.getId();
    Object[] hydratedState = entityEntry.getLoadedState();

    if ( LOG.isDebugEnabled() ) {
      LOG.debugf(
        "Resolving associations for %s",
        MessageHelper.infoString( persister, id, session.getFactory() )
          );
    }

    Type[] types = persister.getPropertyTypes();
    for ( int i = 0; i < hydratedState.length; i++ ) {
      final Object value = hydratedState[i];
      if ( value!=LazyPropertyInitializer.UNFETCHED_PROPERTY && value!=BackrefPropertyAccessor.UNKNOWN ) {
        hydratedState[i] = types[i].resolve( value, session, entity );
      }
    }

    //Must occur after resolving identifiers!
    if ( session.isEventSource() ) {
      preLoadEvent.setEntity( entity ).setState( hydratedState ).setId( id ).setPersister( persister );

      final EventListenerGroup<PreLoadEventListener> listenerGroup = session
          .getFactory()
          .getServiceRegistry()
          .getService( EventListenerRegistry.class )
          .getEventListenerGroup( EventType.PRE_LOAD );
      for ( PreLoadEventListener listener : listenerGroup.listeners() ) {
        listener.onPreLoad( preLoadEvent );
      }
    }

    persister.setPropertyValues( entity, hydratedState );

    final SessionFactoryImplementor factory = session.getFactory();
    if ( persister.hasCache() && session.getCacheMode().isPutEnabled() ) {

      if ( LOG.isDebugEnabled() ) {
        LOG.debugf(
          "Adding entity to second-level cache: %s",
          MessageHelper.infoString( persister, id, session.getFactory() )
            );
      }

      Object version = Versioning.getVersion(hydratedState, persister);
      CacheEntry entry = new CacheEntry(
          hydratedState,
          persister,
          entityEntry.isLoadedWithLazyPropertiesUnfetched(),
          version,
          session,
          entity
      );
      CacheKey cacheKey = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );

      // explicit handling of caching for rows just inserted and then somehow forced to be read
      // from the database *within the same transaction*.  usually this is done by
      //     1) Session#refresh, or
      //     2) Session#clear + some form of load
      //
      // we need to be careful not to clobber the lock here in the cache so that it can be rolled back if need be
      if ( session.getPersistenceContext().wasInsertedDuringTransaction( persister, id ) ) {
        persister.getCacheAccessStrategy().update(
            cacheKey,
            persister.getCacheEntryStructure().structure( entry ),
            version,
            version
        );
      }
      else {
        boolean put = persister.getCacheAccessStrategy().putFromLoad(
            cacheKey,
            persister.getCacheEntryStructure().structure( entry ),
            session.getTimestamp(),
            version,
            useMinimalPuts( session, entityEntry )
        );

        if ( put && factory.getStatistics().isStatisticsEnabled() ) {
          factory.getStatisticsImplementor().secondLevelCachePut( persister.getCacheAccessStrategy().getRegion().getName() );
        }
      }
    }

    boolean isReallyReadOnly = readOnly;
    if ( !persister.isMutable() ) {
      isReallyReadOnly = true;
    }
    else {
      Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() );
      if ( proxy != null ) {
        // there is already a proxy for this impl
        // only set the status to read-only if the proxy is read-only
        isReallyReadOnly = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isReadOnly();
      }
    }
    if ( isReallyReadOnly ) {
      //no need to take a snapshot - this is a
      //performance optimization, but not really
      //important, except for entities with huge
      //mutable property values
      persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY);
    }
    else {
      //take a snapshot
      TypeHelper.deepCopy(
          hydratedState,
          persister.getPropertyTypes(),
          persister.getPropertyUpdateability(),
          hydratedState,  //after setting values to object, entityMode
          session
      );
      persistenceContext.setEntryStatus(entityEntry, Status.MANAGED);
    }

    persister.afterInitialize(
        entity,
        entityEntry.isLoadedWithLazyPropertiesUnfetched(),
View Full Code Here

TOP

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

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.