Package org.hibernate.event

Examples of org.hibernate.event.EventSource


   *
   * @throws HibernateException
   */
  public void onDelete(DeleteEvent event, Set transientEntities) throws HibernateException {

    final EventSource source = event.getSession();

    final PersistenceContext persistenceContext = source.getPersistenceContext();
    Object entity = persistenceContext.unproxyAndReassociate( event.getObject() );

    EntityEntry entityEntry = persistenceContext.getEntry( entity );
    final EntityPersister persister;
    final Serializable id;
    final Object version;

    if ( entityEntry == null ) {
      log.trace( "entity was not persistent in delete processing" );

      persister = source.getEntityPersister( event.getEntityName(), entity );

      if ( ForeignKeys.isTransient( persister.getEntityName(), entity, null, source ) ) {
        deleteTransientEntity( source, entity, event.isCascadeDeleteEnabled(), persister, transientEntities );
        // EARLY EXIT!!!
        return;
      }
      else {
        performDetachedEntityDeletionCheck( event );
      }

      id = persister.getIdentifier( entity, source.getEntityMode() );

      if ( id == null ) {
        throw new TransientObjectException(
            "the detached instance passed to delete() had a null identifier"
        );
      }

      EntityKey key = new EntityKey( id, persister, source.getEntityMode() );

      persistenceContext.checkUniqueness( key, entity );

      new OnUpdateVisitor( source, id, entity ).process( entity, persister );

      version = persister.getVersion( entity, source.getEntityMode() );

      entityEntry = persistenceContext.addEntity(
          entity,
          Status.MANAGED,
          persister.getPropertyValues( entity, source.getEntityMode() ),
          key,
          version,
          LockMode.NONE,
          true,
          persister,
          false,
          false
      );
    }
    else {
      log.trace( "deleting a persistent instance" );

      if ( entityEntry.getStatus() == Status.DELETED || entityEntry.getStatus() == Status.GONE ) {
        log.trace( "object was already deleted" );
        return;
      }
      persister = entityEntry.getPersister();
      id = entityEntry.getId();
      version = entityEntry.getVersion();
    }

    /*if ( !persister.isMutable() ) {
      throw new HibernateException(
          "attempted to delete an object of immutable class: " +
          MessageHelper.infoString(persister)
        );
    }*/

    if ( invokeDeleteLifecycle( source, entity, persister ) ) {
      return;
    }

    deleteEntity( source, entity, entityEntry, event.isCascadeDeleteEnabled(), persister, transientEntities );

    if ( source.getFactory().getSettings().isIdentifierRollbackEnabled() ) {
      persister.resetIdentifier( entity, id, version, source.getEntityMode() );
    }
  }
View Full Code Here


      final Serializable id,
      final EntityPersister persister,
      final LoadEvent event) throws HibernateException {

    final Object optionalObject = event.getInstanceToLoad();
    final EventSource session = event.getSession();
    final SessionFactoryImplementor factory = session.getFactory();

    if ( log.isTraceEnabled() ) {
      log.trace(
          "assembling entity from second-level cache: " +
          MessageHelper.infoString( persister, id, factory )
        );
    }

    EntityPersister subclassPersister = factory.getEntityPersister( entry.getSubclass() );
    Object result = optionalObject == null ?
        session.instantiate( subclassPersister, id ) : optionalObject;

    // make it circular-reference safe
    TwoPhaseLoad.addUninitializedCachedEntity(
        new EntityKey( id, subclassPersister, session.getEntityMode() ),
        result,
        subclassPersister,
        LockMode.NONE,
        entry.areLazyPropertiesUnfetched(),
        entry.getVersion(),
        session
      );

    Type[] types = subclassPersister.getPropertyTypes();
    Object[] values = entry.assemble( result, id, subclassPersister, session.getInterceptor(), session ); // intializes result by side-effect
    TypeFactory.deepCopy(
        values,
        types,
        subclassPersister.getPropertyUpdateability(),
        values,
        session
      );

    Object version = Versioning.getVersion( values, subclassPersister );
    if ( log.isTraceEnabled() ) log.trace( "Cached Version: " + version );

    final PersistenceContext persistenceContext = session.getPersistenceContext();
    persistenceContext.addEntry(
        result,
        Status.MANAGED,
        values,
        null,
        id,
        version,
        LockMode.NONE,
        true,
        subclassPersister,
        false,
        entry.areLazyPropertiesUnfetched()
      );
    subclassPersister.afterInitialize( result, entry.areLazyPropertiesUnfetched(), session );
    persistenceContext.initializeNonLazyCollections();
    // upgrade the lock if necessary:
    //lock(result, lockMode);

    //PostLoad is needed for EJB3
    //TODO: reuse the PostLoadEvent...
    PostLoadEvent postLoadEvent = new PostLoadEvent(session).setEntity(result)
        .setId(id).setPersister(persister);
    PostLoadEventListener[] listeners = session.getListeners().getPostLoadEventListeners();
    for ( int i = 0; i < listeners.length; i++ ) {
      listeners[i].onPostLoad(postLoadEvent);
    }

    return result;
View Full Code Here

   * an update action, if necessary
   */
  public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
    final Object entity = event.getEntity();
    final EntityEntry entry = event.getEntityEntry();
    final EventSource session = event.getSession();
    final EntityPersister persister = entry.getPersister();
    final Status status = entry.getStatus();
    final EntityMode entityMode = session.getEntityMode();
    final Type[] types = persister.getPropertyTypes();

    final boolean mightBeDirty = entry.requiresDirtyCheck(entity);

    final Object[] values = getValues( entity, entry, entityMode, mightBeDirty, session );
View Full Code Here

  }

  private boolean scheduleUpdate(final FlushEntityEvent event) {
   
    final EntityEntry entry = event.getEntityEntry();
    final EventSource session = event.getSession();
    final Object entity = event.getEntity();
    final Status status = entry.getStatus();
    final EntityMode entityMode = session.getEntityMode();
    final EntityPersister persister = entry.getPersister();
    final Object[] values = event.getPropertyValues();
   
    if ( log.isTraceEnabled() ) {
      if ( status == Status.DELETED ) {
        log.trace(
            "Updating deleted entity: " +
            MessageHelper.infoString( persister, entry.getId(), session.getFactory() )
          );
      }
      else {
        log.trace(
            "Updating entity: " +
            MessageHelper.infoString( persister, entry.getId(), session.getFactory()  )
          );
      }
    }

    final boolean intercepted;
    if ( !entry.isBeingReplicated() ) {
      // give the Interceptor a chance to process property values, if the properties
      // were modified by the Interceptor, we need to set them back to the object
      intercepted = handleInterception( event );
    }
    else {
      intercepted = false;
    }

    validate( entity, persister, status, entityMode );

    // increment the version number (if necessary)
    final Object nextVersion = getNextVersion(event);

    // if it was dirtied by a collection only
    int[] dirtyProperties = event.getDirtyProperties();
    if ( event.isDirtyCheckPossible() && dirtyProperties == null ) {
      if ( ! intercepted && !event.hasDirtyCollection() ) {
        throw new AssertionFailure( "dirty, but no dirty properties" );
      }
      dirtyProperties = ArrayHelper.EMPTY_INT_ARRAY;
    }

    // check nullability but do not perform command execute
    // we'll use scheduled updates for that.
    new Nullability(session).checkNullability( values, persister, true );

    // schedule the update
    // note that we intentionally do _not_ pass in currentPersistentState!
    session.getActionQueue().addAction(
        new EntityUpdateAction(
            entry.getId(),
            values,
            dirtyProperties,
            event.hasDirtyCollection(),
View Full Code Here

   * @param event The replicate event to be handled.
   *
   * @throws TransientObjectException An invalid attempt to replicate a transient entity.
   */
  public void onReplicate(ReplicateEvent event) {
    final EventSource source = event.getSession();
    if ( source.getPersistenceContext().reassociateIfUninitializedProxy( event.getObject() ) ) {
      log.trace( "uninitialized proxy passed to replicate()" );
      return;
    }

    Object entity = source.getPersistenceContext().unproxyAndReassociate( event.getObject() );

    if ( source.getPersistenceContext().isEntryFor( entity ) ) {
      log.trace( "ignoring persistent instance passed to replicate()" );
      //hum ... should we cascade anyway? throw an exception? fine like it is?
      return;
    }

    EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );

    // get the id from the object
    /*if ( persister.isUnsaved(entity, source) ) {
      throw new TransientObjectException("transient instance passed to replicate()");
    }*/
    Serializable id = persister.getIdentifier( entity, source.getEntityMode() );
    if ( id == null ) {
      throw new TransientObjectException( "instance with null id passed to replicate()" );
    }

    final ReplicationMode replicationMode = event.getReplicationMode();

    final Object oldVersion;
    if ( replicationMode == ReplicationMode.EXCEPTION ) {
      //always do an INSERT, and let it fail by constraint violation
      oldVersion = null;
    }
    else {
      //what is the version on the database?
      oldVersion = persister.getCurrentVersion( id, source );     
    }

    if ( oldVersion != null ) {      
      if ( log.isTraceEnabled() ) {
        log.trace(
            "found existing row for " +
                MessageHelper.infoString( persister, id, source.getFactory() )
        );
      }

      /// HHH-2378
      final Object realOldVersion = persister.isVersioned() ? oldVersion : null;
     
      boolean canReplicate = replicationMode.shouldOverwriteCurrentVersion(
          entity,
          realOldVersion,
          persister.getVersion( entity, source.getEntityMode() ),
          persister.getVersionType()
      );

      if ( canReplicate ) {
        //will result in a SQL UPDATE:
        performReplication( entity, id, realOldVersion, persister, replicationMode, source );
      }
      else {
        //else do nothing (don't even reassociate object!)
        log.trace( "no need to replicate" );
      }

      //TODO: would it be better to do a refresh from db?
    }
    else {
      // no existing row - do an insert
      if ( log.isTraceEnabled() ) {
        log.trace(
            "no existing row, replicating new instance " +
                MessageHelper.infoString( persister, id, source.getFactory() )
        );
      }

      final boolean regenerate = persister.isIdentifierAssignedByInsert(); // prefer re-generation of identity!
      final EntityKey key = regenerate ?
          null : new EntityKey( id, persister, source.getEntityMode() );

      performSaveOrReplicate(
          entity,
          key,
          persister,
View Full Code Here

   *
   * @param event The evict event to be handled.
   * @throws HibernateException
   */
  public void onEvict(EvictEvent event) throws HibernateException {
    EventSource source = event.getSession();
    final Object object = event.getObject();
    final PersistenceContext persistenceContext = source.getPersistenceContext();

    if ( object instanceof HibernateProxy ) {
      LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer();
      Serializable id = li.getIdentifier();
      EntityPersister persister = source.getFactory().getEntityPersister( li.getEntityName() );
      if ( id == null ) {
        throw new IllegalArgumentException("null identifier");
      }
      EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
      persistenceContext.removeProxy( key );
      if ( !li.isUninitialized() ) {
        final Object entity = persistenceContext.removeEntity(key);
        if ( entity != null ) {
          EntityEntry e = event.getSession().getPersistenceContext().removeEntry(entity);
          doEvict( entity, key, e.getPersister(), event.getSession() );
        }
      }
      li.setSession( null );
    }
    else {
      EntityEntry e = persistenceContext.removeEntry( object );
      if ( e != null ) {
        EntityKey key = new EntityKey( e.getId(), e.getPersister(), source.getEntityMode()  );
        persistenceContext.removeEntity( key );
        doEvict( object, key, e.getPersister(), source );
      }
     
    }
View Full Code Here

   */
  protected Serializable entityIsTransient(SaveOrUpdateEvent event) {

    log.trace( "saving transient instance" );

    final EventSource source = event.getSession();

    EntityEntry entityEntry = event.getEntry();
    if ( entityEntry != null ) {
      if ( entityEntry.getStatus() == Status.DELETED ) {
        source.forceFlush( entityEntry );
      }
      else {
        throw new AssertionFailure( "entity was persistent" );
      }
    }

    Serializable id = saveWithGeneratedOrRequestedId( event );

    source.getPersistenceContext().reassociateProxy( event.getObject(), id );

    return id;
  }
View Full Code Here

                    persister, event.getRequestedId(), event.getSession().getFactory()
                )
        );
      }

      final EventSource source = event.getSession();

      EntityKey key = new EntityKey( event.getRequestedId(), persister, source.getEntityMode() );

      source.getPersistenceContext().checkUniqueness( key, entity );

      if ( invokeUpdateLifecycle( entity, persister, source ) ) {
        reassociate( event, event.getObject(), event.getRequestedId(), persister );
        return;
      }

      // this is a transient object with existing persistent state not loaded by the session

      new OnUpdateVisitor( source, event.getRequestedId(), entity ).process( entity, persister );

      //TODO: put this stuff back in to read snapshot from
      //      the second-level cache (needs some extra work)
      /*Object[] cachedState = null;

      if ( persister.hasCache() ) {
        CacheEntry entry = (CacheEntry) persister.getCache()
            .get( event.getRequestedId(), source.getTimestamp() );
          cachedState = entry==null ?
              null :
              entry.getState(); //TODO: half-assemble this stuff
      }*/

      source.getPersistenceContext().addEntity(
          entity,
          Status.MANAGED,
          null, //cachedState,
          key,
          persister.getVersion( entity, source.getEntityMode() ),
          LockMode.NONE,
          true,
          persister,
          false,
          true //assume true, since we don't really know, and it doesn't matter
      );

      persister.afterReassociate( entity, source );

      if ( log.isTraceEnabled() ) {
        log.trace(
            "updating " +
                MessageHelper.infoString( persister, event.getRequestedId(), source.getFactory() )
        );
      }

      cascadeOnUpdate( event, persister, entity );

View Full Code Here

   * @param event The event currently being processed.
   * @param persister The defined persister for the entity being updated.
   * @param entity The entity being updated.
   */
  private void cascadeOnUpdate(SaveOrUpdateEvent event, EntityPersister persister, Object entity) {
    EventSource source = event.getSession();
    source.getPersistenceContext().incrementCascadeLevel();
    try {
      new Cascade( CascadingAction.SAVE_UPDATE, Cascade.AFTER_UPDATE, source )
          .cascade( persister, entity );
    }
    finally {
      source.getPersistenceContext().decrementCascadeLevel();
    }
  }
View Full Code Here

   
    if ( collection == CollectionType.UNFETCHED_COLLECTION ) {
      return null;
    }

    EventSource session = getSession();
    CollectionPersister persister = session.getFactory().getCollectionPersister( type.getRole() );

    final Serializable collectionKey = extractCollectionKeyFromOwner( persister );
    if ( collection!=null && (collection instanceof PersistentCollection) ) {
      PersistentCollection wrapper = (PersistentCollection) collection;
      if ( wrapper.setCurrentSession(session) ) {
View Full Code Here

TOP

Related Classes of org.hibernate.event.EventSource

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.