Search in sources :

Example 46 with HibernateProxy

use of org.hibernate.proxy.HibernateProxy in project hibernate-orm by hibernate.

the class PersistenceUtilHelper method isLoadedWithReference.

/**
 * Is the given attribute (by name) loaded?  This form must take care to not access the attribute (trigger
 * initialization).
 *
 * @param entity The entity
 * @param attributeName The name of the attribute to check
 * @param cache The cache we maintain of attribute resolutions
 *
 * @return The LoadState
 */
public static LoadState isLoadedWithReference(Object entity, String attributeName, MetadataCache cache) {
    if (entity instanceof HibernateProxy) {
        final LazyInitializer li = ((HibernateProxy) entity).getHibernateLazyInitializer();
        if (li.isUninitialized()) {
            // we have an uninitialized proxy, the attribute cannot be loaded
            return LoadState.NOT_LOADED;
        } else {
            // swap the proxy with target (for proper class name resolution)
            entity = li.getImplementation();
        }
    }
    try {
        final Class entityClass = entity.getClass();
        final Object attributeValue = cache.getClassMetadata(entityClass).getAttributeAccess(attributeName).extractValue(entity);
        return isLoaded(attributeValue);
    } catch (AttributeExtractionException ignore) {
        return LoadState.UNKNOWN;
    }
}
Also used : LazyInitializer(org.hibernate.proxy.LazyInitializer) HibernateProxy(org.hibernate.proxy.HibernateProxy)

Example 47 with HibernateProxy

use of org.hibernate.proxy.HibernateProxy in project hibernate-orm by hibernate.

the class SerializableProxy method readResolve.

/**
 * Deserialization hook.  This method is called by JDK deserialization.  We use this hook
 * to replace the serial form with a live form.
 *
 * @return The live form.
 */
private Object readResolve() {
    HibernateProxy proxy = JavassistProxyFactory.deserializeProxy(this);
    setReadOnlyBeforeAttachedToSession((JavassistLazyInitializer) proxy.getHibernateLazyInitializer());
    return proxy;
}
Also used : HibernateProxy(org.hibernate.proxy.HibernateProxy)

Example 48 with HibernateProxy

use of org.hibernate.proxy.HibernateProxy in project hibernate-orm by hibernate.

the class SessionImpl method contains.

@Override
public boolean contains(Object object) {
    checkOpen();
    checkTransactionSynchStatus();
    if (object == null) {
        return false;
    }
    try {
        if (object instanceof HibernateProxy) {
            // do not use proxiesByKey, since not all
            // proxies that point to this session's
            // instances are in that collection!
            LazyInitializer li = ((HibernateProxy) object).getHibernateLazyInitializer();
            if (li.isUninitialized()) {
                // the underlying instance will be "contained"
                return li.getSession() == this;
            } else {
                // if it is initialized, see if the underlying
                // instance is contained, since we need to
                // account for the fact that it might have been
                // evicted
                object = li.getImplementation();
            }
        }
        // A session is considered to contain an entity only if the entity has
        // an entry in the session's persistence context and the entry reports
        // that the entity has not been removed
        EntityEntry entry = persistenceContext.getEntry(object);
        delayedAfterCompletion();
        if (entry == null) {
            if (!HibernateProxy.class.isInstance(object) && persistenceContext.getEntry(object) == null) {
                // check if it is even an entity -> if not throw an exception (per JPA)
                try {
                    final String entityName = getEntityNameResolver().resolveEntityName(object);
                    if (entityName == null) {
                        throw new IllegalArgumentException("Could not resolve entity-name [" + object + "]");
                    }
                    getSessionFactory().getMetamodel().entityPersister(entityName);
                } catch (HibernateException e) {
                    throw new IllegalArgumentException("Not an entity [" + object.getClass() + "]", e);
                }
            }
            return false;
        } else {
            return entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE;
        }
    } catch (MappingException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    } catch (RuntimeException e) {
        throw exceptionConverter.convert(e);
    }
}
Also used : LazyInitializer(org.hibernate.proxy.LazyInitializer) EntityEntry(org.hibernate.engine.spi.EntityEntry) HibernateException(org.hibernate.HibernateException) HibernateProxy(org.hibernate.proxy.HibernateProxy) UnknownSqlResultSetMappingException(org.hibernate.procedure.UnknownSqlResultSetMappingException) MappingException(org.hibernate.MappingException)

Example 49 with HibernateProxy

use of org.hibernate.proxy.HibernateProxy in project hibernate-orm by hibernate.

the class SessionImpl method contains.

@Override
public boolean contains(String entityName, Object object) {
    checkOpen();
    checkTransactionSynchStatus();
    if (object == null) {
        return false;
    }
    try {
        if (!HibernateProxy.class.isInstance(object) && persistenceContext.getEntry(object) == null) {
            // check if it is an entity -> if not throw an exception (per JPA)
            try {
                getSessionFactory().getMetamodel().entityPersister(entityName);
            } catch (HibernateException e) {
                throw new IllegalArgumentException("Not an entity [" + entityName + "] : " + object);
            }
        }
        if (object instanceof HibernateProxy) {
            // do not use proxiesByKey, since not all
            // proxies that point to this session's
            // instances are in that collection!
            LazyInitializer li = ((HibernateProxy) object).getHibernateLazyInitializer();
            if (li.isUninitialized()) {
                // the underlying instance will be "contained"
                return li.getSession() == this;
            } else {
                // if it is initialized, see if the underlying
                // instance is contained, since we need to
                // account for the fact that it might have been
                // evicted
                object = li.getImplementation();
            }
        }
        // A session is considered to contain an entity only if the entity has
        // an entry in the session's persistence context and the entry reports
        // that the entity has not been removed
        EntityEntry entry = persistenceContext.getEntry(object);
        delayedAfterCompletion();
        return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE;
    } catch (MappingException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    } catch (RuntimeException e) {
        throw exceptionConverter.convert(e);
    }
}
Also used : LazyInitializer(org.hibernate.proxy.LazyInitializer) EntityEntry(org.hibernate.engine.spi.EntityEntry) HibernateException(org.hibernate.HibernateException) HibernateProxy(org.hibernate.proxy.HibernateProxy) UnknownSqlResultSetMappingException(org.hibernate.procedure.UnknownSqlResultSetMappingException) MappingException(org.hibernate.MappingException)

Example 50 with HibernateProxy

use of org.hibernate.proxy.HibernateProxy in project hibernate-orm by hibernate.

the class TwoPhaseLoad method doInitializeEntity.

private static void doInitializeEntity(final Object entity, final EntityEntry entityEntry, final boolean readOnly, final SharedSessionContractImplementor session, final PreLoadEvent preLoadEvent) throws HibernateException {
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    final EntityPersister persister = entityEntry.getPersister();
    final Serializable id = entityEntry.getId();
    final Object[] hydratedState = entityEntry.getLoadedState();
    final boolean debugEnabled = LOG.isDebugEnabled();
    if (debugEnabled) {
        LOG.debugf("Resolving associations for %s", MessageHelper.infoString(persister, id, session.getFactory()));
    }
    String entityName = persister.getEntityName();
    String[] propertyNames = persister.getPropertyNames();
    final Type[] types = persister.getPropertyTypes();
    for (int i = 0; i < hydratedState.length; i++) {
        final Object value = hydratedState[i];
        Boolean overridingEager = getOverridingEager(session, entityName, propertyNames[i], types[i]);
        if (value == LazyPropertyInitializer.UNFETCHED_PROPERTY) {
            // No resolution is necessary, unless the lazy property is a collection.
            if (types[i].isCollectionType()) {
                // IMPLEMENTATION NOTE: this is a lazy collection property on a bytecode-enhanced entity.
                // HHH-10989: We need to resolve the collection so that a CollectionReference is added to StatefulPersistentContext.
                // As mentioned above, hydratedState[i] needs to remain LazyPropertyInitializer.UNFETCHED_PROPERTY
                // so do not assign the resolved, unitialized PersistentCollection back to hydratedState[i].
                types[i].resolve(value, session, entity, overridingEager);
            }
        } else if (value != PropertyAccessStrategyBackRefImpl.UNKNOWN) {
            // we know value != LazyPropertyInitializer.UNFETCHED_PROPERTY
            hydratedState[i] = types[i].resolve(value, session, entity, overridingEager);
        }
    }
    // 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.canWriteToCache() && session.getCacheMode().isPutEnabled()) {
        if (debugEnabled) {
            LOG.debugf("Adding entity to second-level cache: %s", MessageHelper.infoString(persister, id, session.getFactory()));
        }
        final Object version = Versioning.getVersion(hydratedState, persister);
        final CacheEntry entry = persister.buildCacheEntry(entity, hydratedState, version, session);
        final EntityDataAccess cache = persister.getCacheAccessStrategy();
        final Object cacheKey = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
        // 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)) {
            cache.update(session, cacheKey, persister.getCacheEntryStructure().structure(entry), version, version);
        } else {
            final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
            try {
                eventListenerManager.cachePutStart();
                final boolean put = cache.putFromLoad(session, cacheKey, persister.getCacheEntryStructure().structure(entry), version, useMinimalPuts(session, entityEntry));
                if (put && factory.getStatistics().isStatisticsEnabled()) {
                    factory.getStatistics().entityCachePut(StatsHelper.INSTANCE.getRootEntityRole(persister), cache.getRegion().getName());
                }
            } finally {
                eventListenerManager.cachePutEnd();
            }
        }
    }
    if (persister.hasNaturalIdentifier()) {
        persistenceContext.getNaturalIdHelper().cacheNaturalIdCrossReferenceFromLoad(persister, id, persistenceContext.getNaturalIdHelper().extractNaturalIdValues(hydratedState, persister));
    }
    boolean isReallyReadOnly = readOnly;
    if (!persister.isMutable()) {
        isReallyReadOnly = true;
    } else {
        final 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(), // after setting values to object
        hydratedState, session);
        persistenceContext.setEntryStatus(entityEntry, Status.MANAGED);
    }
    persister.afterInitialize(entity, session);
    if (debugEnabled) {
        LOG.debugf("Done materializing entity %s", MessageHelper.infoString(persister, id, session.getFactory()));
    }
    if (factory.getStatistics().isStatisticsEnabled()) {
        factory.getStatistics().loadEntity(persister.getEntityName());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) PreLoadEventListener(org.hibernate.event.spi.PreLoadEventListener) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) HibernateProxy(org.hibernate.proxy.HibernateProxy) EventListenerRegistry(org.hibernate.event.service.spi.EventListenerRegistry) EventType(org.hibernate.event.spi.EventType) Type(org.hibernate.type.Type) SessionEventListenerManager(org.hibernate.engine.spi.SessionEventListenerManager) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess)

Aggregations

HibernateProxy (org.hibernate.proxy.HibernateProxy)130 Session (org.hibernate.Session)58 Test (org.junit.Test)56 LazyInitializer (org.hibernate.proxy.LazyInitializer)33 DefaultPostLoaderDao (org.broadleafcommerce.common.persistence.DefaultPostLoaderDao)16 PostLoaderDao (org.broadleafcommerce.common.persistence.PostLoaderDao)16 EntityEntry (org.hibernate.engine.spi.EntityEntry)13 Serializable (java.io.Serializable)11 Transaction (org.hibernate.Transaction)10 TransientObjectException (org.hibernate.TransientObjectException)10 EntityPersister (org.hibernate.persister.entity.EntityPersister)10 HibernateException (org.hibernate.HibernateException)8 AdminPresentationMergeOverride (org.broadleafcommerce.common.presentation.override.AdminPresentationMergeOverride)5 EntityKey (org.hibernate.engine.spi.EntityKey)4 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)4 Iterator (java.util.Iterator)3 ObjectDeletedException (org.hibernate.ObjectDeletedException)3 EventSource (org.hibernate.event.spi.EventSource)3 BigDecimal (java.math.BigDecimal)2