Search in sources :

Example 1 with EnhancementAsProxyLazinessInterceptor

use of org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor in project hibernate-orm by hibernate.

the class WrapVisitor method processArrayOrNewCollection.

final Object processArrayOrNewCollection(Object collection, CollectionType collectionType) throws HibernateException {
    final SessionImplementor session = getSession();
    if (collection == null) {
        // do nothing
        return null;
    } else {
        final CollectionPersister persister = session.getFactory().getRuntimeMetamodels().getMappingMetamodel().getCollectionDescriptor(collectionType.getRole());
        final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
        // TODO: move into collection type, so we can use polymorphism!
        if (collectionType.hasHolder()) {
            if (collection == CollectionType.UNFETCHED_COLLECTION) {
                return null;
            }
            PersistentCollection<?> ah = persistenceContext.getCollectionHolder(collection);
            if (ah == null) {
                ah = collectionType.wrap(session, collection);
                persistenceContext.addNewCollection(persister, ah);
                persistenceContext.addCollectionHolder(ah);
            }
            return null;
        } else {
            if (entity instanceof PersistentAttributeInterceptable) {
                PersistentAttributeInterceptor attributeInterceptor = ((PersistentAttributeInterceptable) entity).$$_hibernate_getInterceptor();
                if (attributeInterceptor instanceof EnhancementAsProxyLazinessInterceptor) {
                    return null;
                }
            }
            final PersistentCollection<?> persistentCollection = collectionType.wrap(session, collection);
            persistenceContext.addNewCollection(persister, persistentCollection);
            if (LOG.isTraceEnabled()) {
                LOG.tracev("Wrapped collection in role: {0}", collectionType.getRole());
            }
            // Force a substitution!
            return persistentCollection;
        }
    }
}
Also used : CollectionPersister(org.hibernate.persister.collection.CollectionPersister) PersistentAttributeInterceptor(org.hibernate.engine.spi.PersistentAttributeInterceptor) PersistentAttributeInterceptable(org.hibernate.engine.spi.PersistentAttributeInterceptable) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) EnhancementAsProxyLazinessInterceptor(org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor)

Example 2 with EnhancementAsProxyLazinessInterceptor

use of org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor in project hibernate-orm by hibernate.

the class DefaultMergeEventListener method onMerge.

/**
 * Handle the given merge event.
 *
 * @param event The merge event to be handled.
 */
public void onMerge(MergeEvent event, MergeContext copiedAlready) throws HibernateException {
    final EventSource source = event.getSession();
    final Object original = event.getOriginal();
    if (original != null) {
        final Object entity;
        if (original instanceof HibernateProxy) {
            LazyInitializer li = ((HibernateProxy) original).getHibernateLazyInitializer();
            if (li.isUninitialized()) {
                LOG.trace("Ignoring uninitialized proxy");
                event.setResult(source.load(li.getEntityName(), li.getInternalIdentifier()));
                // EARLY EXIT!
                return;
            } else {
                entity = li.getImplementation();
            }
        } else if (original instanceof PersistentAttributeInterceptable) {
            final PersistentAttributeInterceptable interceptable = (PersistentAttributeInterceptable) original;
            final PersistentAttributeInterceptor interceptor = interceptable.$$_hibernate_getInterceptor();
            if (interceptor instanceof EnhancementAsProxyLazinessInterceptor) {
                final EnhancementAsProxyLazinessInterceptor proxyInterceptor = (EnhancementAsProxyLazinessInterceptor) interceptor;
                LOG.trace("Ignoring uninitialized enhanced-proxy");
                event.setResult(source.load(proxyInterceptor.getEntityName(), proxyInterceptor.getIdentifier()));
                // EARLY EXIT!
                return;
            } else {
                entity = original;
            }
        } else {
            entity = original;
        }
        if (copiedAlready.containsKey(entity) && copiedAlready.isOperatedOn(entity)) {
            LOG.trace("Already in merge process");
            event.setResult(entity);
        } else {
            if (copiedAlready.containsKey(entity)) {
                LOG.trace("Already in copyCache; setting in merge process");
                copiedAlready.setOperatedOn(entity, true);
            }
            event.setEntity(entity);
            EntityState entityState = null;
            // Check the persistence context for an entry relating to this
            // entity to be merged...
            final PersistenceContext persistenceContext = source.getPersistenceContextInternal();
            EntityEntry entry = persistenceContext.getEntry(entity);
            if (entry == null) {
                EntityPersister persister = source.getEntityPersister(event.getEntityName(), entity);
                Object id = persister.getIdentifier(entity, source);
                if (id != null) {
                    final EntityKey key = source.generateEntityKey(id, persister);
                    final Object managedEntity = persistenceContext.getEntity(key);
                    entry = persistenceContext.getEntry(managedEntity);
                    if (entry != null) {
                        // we have specialized case of a detached entity from the
                        // perspective of the merge operation.  Specifically, we
                        // have an incoming entity instance which has a corresponding
                        // entry in the current persistence context, but registered
                        // under a different entity instance
                        entityState = EntityState.DETACHED;
                    }
                }
            }
            if (entityState == null) {
                entityState = EntityState.getEntityState(entity, event.getEntityName(), entry, source, false);
            }
            switch(entityState) {
                case DETACHED:
                    entityIsDetached(event, copiedAlready);
                    break;
                case TRANSIENT:
                    entityIsTransient(event, copiedAlready);
                    break;
                case PERSISTENT:
                    entityIsPersistent(event, copiedAlready);
                    break;
                default:
                    // DELETED
                    throw new ObjectDeletedException("deleted instance passed to merge", null, EventUtil.getLoggableName(event.getEntityName(), entity));
            }
        }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) LazyInitializer(org.hibernate.proxy.LazyInitializer) PersistentAttributeInterceptor(org.hibernate.engine.spi.PersistentAttributeInterceptor) PersistentAttributeInterceptable(org.hibernate.engine.spi.PersistentAttributeInterceptable) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) HibernateProxy(org.hibernate.proxy.HibernateProxy) EnhancementAsProxyLazinessInterceptor(org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor) EntityKey(org.hibernate.engine.spi.EntityKey) EventSource(org.hibernate.event.spi.EventSource) EntityEntry(org.hibernate.engine.spi.EntityEntry) ObjectDeletedException(org.hibernate.ObjectDeletedException)

Example 3 with EnhancementAsProxyLazinessInterceptor

use of org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor in project hibernate-orm by hibernate.

the class AbstractEntityPersister method initializeEnhancedEntityUsedAsProxy.

@Override
public Object initializeEnhancedEntityUsedAsProxy(Object entity, String nameOfAttributeBeingAccessed, SharedSessionContractImplementor session) {
    final BytecodeEnhancementMetadata enhancementMetadata = getEntityMetamodel().getBytecodeEnhancementMetadata();
    final BytecodeLazyAttributeInterceptor currentInterceptor = enhancementMetadata.extractLazyInterceptor(entity);
    if (currentInterceptor instanceof EnhancementAsProxyLazinessInterceptor) {
        final EnhancementAsProxyLazinessInterceptor proxyInterceptor = (EnhancementAsProxyLazinessInterceptor) currentInterceptor;
        final EntityKey entityKey = proxyInterceptor.getEntityKey();
        final Object identifier = entityKey.getIdentifier();
        Object loaded = null;
        if (canReadFromCache && session instanceof EventSource) {
            LoadEvent loadEvent = new LoadEvent(identifier, entity, (EventSource) session, false);
            loaded = CacheEntityLoaderHelper.INSTANCE.loadFromSecondLevelCache(loadEvent, this, entityKey);
        }
        if (loaded == null) {
            loaded = singleIdEntityLoader.load(identifier, entity, LockOptions.NONE, session);
        }
        if (loaded == null) {
            final PersistenceContext persistenceContext = session.getPersistenceContext();
            persistenceContext.removeEntry(entity);
            persistenceContext.removeEntity(entityKey);
            session.getFactory().getEntityNotFoundDelegate().handleEntityNotFound(entityKey.getEntityName(), identifier);
        }
        final LazyAttributeLoadingInterceptor interceptor = enhancementMetadata.injectInterceptor(entity, identifier, session);
        final Object value;
        if (nameOfAttributeBeingAccessed == null) {
            return null;
        } else if (interceptor.isAttributeLoaded(nameOfAttributeBeingAccessed)) {
            value = getPropertyValue(entity, nameOfAttributeBeingAccessed);
        } else {
            value = ((LazyPropertyInitializer) this).initializeLazyProperty(nameOfAttributeBeingAccessed, entity, session);
        }
        return interceptor.readObject(entity, nameOfAttributeBeingAccessed, value);
    }
    throw new IllegalStateException();
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) LazyPropertyInitializer(org.hibernate.bytecode.enhance.spi.LazyPropertyInitializer) EventSource(org.hibernate.event.spi.EventSource) LoadEvent(org.hibernate.event.spi.LoadEvent) LazyAttributeLoadingInterceptor(org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor) BytecodeLazyAttributeInterceptor(org.hibernate.bytecode.enhance.spi.interceptor.BytecodeLazyAttributeInterceptor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) StatefulPersistenceContext(org.hibernate.engine.internal.StatefulPersistenceContext) BytecodeEnhancementMetadata(org.hibernate.bytecode.spi.BytecodeEnhancementMetadata) EnhancementAsProxyLazinessInterceptor(org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor)

Example 4 with EnhancementAsProxyLazinessInterceptor

use of org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor in project hibernate-orm by hibernate.

the class SimpleUpdateTestWithLazyLoading method updateSimpleField.

@Test
public void updateSimpleField() {
    final Statistics stats = sessionFactory().getStatistics();
    stats.clear();
    final String updatedName = "Barrabas_";
    final EntityPersister childPersister = sessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(Child.class.getName());
    final int relativesAttributeIndex = childPersister.getEntityMetamodel().getPropertyIndex("relatives");
    inTransaction(session -> {
        stats.clear();
        Child loadedChild = session.load(Child.class, lastChildID);
        final PersistentAttributeInterceptable interceptable = (PersistentAttributeInterceptable) loadedChild;
        final PersistentAttributeInterceptor interceptor = interceptable.$$_hibernate_getInterceptor();
        MatcherAssert.assertThat(interceptor, instanceOf(EnhancementAsProxyLazinessInterceptor.class));
        final EnhancementAsProxyLazinessInterceptor proxyInterceptor = (EnhancementAsProxyLazinessInterceptor) interceptor;
        loadedChild.setName(updatedName);
        // ^ should have triggered "base fetch group" initialization which would mean a SQL select
        assertEquals(1, stats.getPrepareStatementCount());
        // check that the `#setName` "persisted"
        assertThat(loadedChild.getName(), is(updatedName));
        assertEquals(1, stats.getPrepareStatementCount());
        final EntityEntry entry = session.getPersistenceContext().getEntry(loadedChild);
        assertThat(entry.getLoadedState()[relativesAttributeIndex], is(LazyPropertyInitializer.UNFETCHED_PROPERTY));
        // force a flush - the relatives collection should still be UNFETCHED_PROPERTY afterwards
        session.flush();
        final EntityEntry updatedEntry = session.getPersistenceContext().getEntry(loadedChild);
        assertThat(updatedEntry, sameInstance(entry));
        assertThat(entry.getLoadedState()[relativesAttributeIndex], is(LazyPropertyInitializer.UNFETCHED_PROPERTY));
        session.getEventListenerManager();
    });
    inTransaction(session -> {
        Child loadedChild = session.load(Child.class, lastChildID);
        assertThat(loadedChild.getName(), is(updatedName));
        final EntityEntry entry = session.getPersistenceContext().getEntry(loadedChild);
        assertThat(entry.getLoadedState()[relativesAttributeIndex], is(LazyPropertyInitializer.UNFETCHED_PROPERTY));
    });
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityEntry(org.hibernate.engine.spi.EntityEntry) PersistentAttributeInterceptor(org.hibernate.engine.spi.PersistentAttributeInterceptor) PersistentAttributeInterceptable(org.hibernate.engine.spi.PersistentAttributeInterceptable) Statistics(org.hibernate.stat.Statistics) EnhancementAsProxyLazinessInterceptor(org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor) Test(org.junit.Test)

Example 5 with EnhancementAsProxyLazinessInterceptor

use of org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor in project hibernate-orm by hibernate.

the class StatefulPersistenceContext method unproxyAndReassociate.

@Override
public Object unproxyAndReassociate(Object maybeProxy) throws HibernateException {
    if (maybeProxy instanceof HibernateProxy) {
        final HibernateProxy proxy = (HibernateProxy) maybeProxy;
        final LazyInitializer li = proxy.getHibernateLazyInitializer();
        reassociateProxy(li, proxy);
        // initialize + unwrap the object and return it
        return li.getImplementation();
    } else if (maybeProxy instanceof PersistentAttributeInterceptable) {
        final PersistentAttributeInterceptable interceptable = (PersistentAttributeInterceptable) maybeProxy;
        final PersistentAttributeInterceptor interceptor = interceptable.$$_hibernate_getInterceptor();
        if (interceptor instanceof EnhancementAsProxyLazinessInterceptor) {
            ((EnhancementAsProxyLazinessInterceptor) interceptor).forceInitialize(maybeProxy, null);
        }
        return maybeProxy;
    } else {
        return maybeProxy;
    }
}
Also used : LazyInitializer(org.hibernate.proxy.LazyInitializer) PersistentAttributeInterceptor(org.hibernate.engine.spi.PersistentAttributeInterceptor) PersistentAttributeInterceptable(org.hibernate.engine.spi.PersistentAttributeInterceptable) HibernateProxy(org.hibernate.proxy.HibernateProxy) EnhancementAsProxyLazinessInterceptor(org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor)

Aggregations

EnhancementAsProxyLazinessInterceptor (org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor)13 PersistentAttributeInterceptable (org.hibernate.engine.spi.PersistentAttributeInterceptable)11 PersistentAttributeInterceptor (org.hibernate.engine.spi.PersistentAttributeInterceptor)10 HibernateProxy (org.hibernate.proxy.HibernateProxy)9 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)5 LazyInitializer (org.hibernate.proxy.LazyInitializer)5 EntityEntry (org.hibernate.engine.spi.EntityEntry)3 EntityKey (org.hibernate.engine.spi.EntityKey)3 EventSource (org.hibernate.event.spi.EventSource)3 EntityPersister (org.hibernate.persister.entity.EntityPersister)3 ObjectDeletedException (org.hibernate.ObjectDeletedException)2 BytecodeLazyAttributeInterceptor (org.hibernate.bytecode.enhance.spi.interceptor.BytecodeLazyAttributeInterceptor)2 BytecodeEnhancementMetadata (org.hibernate.bytecode.spi.BytecodeEnhancementMetadata)2 PersistentCollection (org.hibernate.collection.spi.PersistentCollection)2 StatefulPersistenceContext (org.hibernate.engine.internal.StatefulPersistenceContext)2 CollectionPersister (org.hibernate.persister.collection.CollectionPersister)2 Statistics (org.hibernate.stat.Statistics)2 Test (org.junit.Test)2 Serializable (java.io.Serializable)1 CustomEntityDirtinessStrategy (org.hibernate.CustomEntityDirtinessStrategy)1