Search in sources :

Example 6 with PersistenceContext

use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.

the class DefaultEvictEventListener method onEvict.

/**
	 * Handle the given evict event.
	 *
	 * @param event The evict event to be handled.
	 *
	 * @throws HibernateException
	 */
public void onEvict(EvictEvent event) throws HibernateException {
    final Object object = event.getObject();
    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) {
                throw new IllegalArgumentException("Non-entity object instance passed to evict : " + object);
            }
        }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) LazyInitializer(org.hibernate.proxy.LazyInitializer) Serializable(java.io.Serializable) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) HibernateProxy(org.hibernate.proxy.HibernateProxy) HibernateException(org.hibernate.HibernateException) EntityKey(org.hibernate.engine.spi.EntityKey) EventSource(org.hibernate.event.spi.EventSource) EntityEntry(org.hibernate.engine.spi.EntityEntry)

Example 7 with PersistenceContext

use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.

the class DefaultFlushEventListener method onFlush.

/** Handle the given flush event.
	 *
	 * @param event The flush event to be handled.
	 * @throws HibernateException
	 */
public void onFlush(FlushEvent event) throws HibernateException {
    final EventSource source = event.getSession();
    final PersistenceContext persistenceContext = source.getPersistenceContext();
    if (persistenceContext.getNumberOfManagedEntities() > 0 || persistenceContext.getCollectionEntries().size() > 0) {
        try {
            source.getEventListenerManager().flushStart();
            flushEverythingToExecutions(event);
            performExecutions(source);
            postFlush(source);
        } finally {
            source.getEventListenerManager().flushEnd(event.getNumberOfEntitiesProcessed(), event.getNumberOfCollectionsProcessed());
        }
        postPostFlush(source);
        if (source.getFactory().getStatistics().isStatisticsEnabled()) {
            source.getFactory().getStatistics().flush();
        }
    }
}
Also used : EventSource(org.hibernate.event.spi.EventSource) PersistenceContext(org.hibernate.engine.spi.PersistenceContext)

Example 8 with PersistenceContext

use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.

the class DefaultInitializeCollectionEventListener method initializeCollectionFromCache.

/**
	 * Try to initialize a collection from the cache
	 *
	 * @param id The id of the collection of initialize
	 * @param persister The collection persister
	 * @param collection The collection to initialize
	 * @param source The originating session
	 *
	 * @return true if we were able to initialize the collection from the cache;
	 *         false otherwise.
	 */
private boolean initializeCollectionFromCache(Serializable id, CollectionPersister persister, PersistentCollection collection, SessionImplementor source) {
    if (!source.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters(source)) {
        LOG.trace("Disregarding cached version (if any) of collection due to enabled filters");
        return false;
    }
    final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled();
    if (!useCache) {
        return false;
    }
    final SessionFactoryImplementor factory = source.getFactory();
    final CollectionRegionAccessStrategy cacheAccessStrategy = persister.getCacheAccessStrategy();
    final Object ck = cacheAccessStrategy.generateCacheKey(id, persister, factory, source.getTenantIdentifier());
    final Object ce = CacheHelper.fromSharedCache(source, ck, persister.getCacheAccessStrategy());
    if (factory.getStatistics().isStatisticsEnabled()) {
        if (ce == null) {
            factory.getStatisticsImplementor().secondLevelCacheMiss(cacheAccessStrategy.getRegion().getName());
        } else {
            factory.getStatisticsImplementor().secondLevelCacheHit(cacheAccessStrategy.getRegion().getName());
        }
    }
    if (ce == null) {
        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;
}
Also used : CollectionCacheEntry(org.hibernate.cache.spi.entry.CollectionCacheEntry) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy)

Example 9 with PersistenceContext

use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.

the class DefaultLoadEventListener method proxyOrLoad.

/**
	 * Based on configured options, will either return a pre-existing proxy,
	 * generate a new proxy, or perform an actual load.
	 *
	 * @param event The initiating load request event
	 * @param persister The persister corresponding to the entity to be loaded
	 * @param keyToLoad The key of the entity to be loaded
	 * @param options The defined load options
	 *
	 * @return The result of the proxy/load operation.
	 */
private Object proxyOrLoad(final LoadEvent event, final EntityPersister persister, final EntityKey keyToLoad, final LoadEventListener.LoadType options) {
    if (traceEnabled) {
        LOG.tracev("Loading entity: {0}", MessageHelper.infoString(persister, event.getEntityId(), event.getSession().getFactory()));
    }
    // this class has no proxies (so do a shortcut)
    if (!persister.hasProxy()) {
        return load(event, persister, keyToLoad, options);
    }
    final PersistenceContext persistenceContext = event.getSession().getPersistenceContext();
    // look for a proxy
    Object proxy = persistenceContext.getProxy(keyToLoad);
    if (proxy != null) {
        return returnNarrowedProxy(event, persister, keyToLoad, options, persistenceContext, proxy);
    }
    if (options.isAllowProxyCreation()) {
        return createProxyIfNecessary(event, persister, keyToLoad, options, persistenceContext);
    }
    // return a newly loaded object
    return load(event, persister, keyToLoad, options);
}
Also used : PersistenceContext(org.hibernate.engine.spi.PersistenceContext) StatefulPersistenceContext(org.hibernate.engine.internal.StatefulPersistenceContext)

Example 10 with PersistenceContext

use of org.hibernate.engine.spi.PersistenceContext in project hibernate-orm by hibernate.

the class DefaultLoadEventListener method assembleCacheEntry.

private Object assembleCacheEntry(final StandardCacheEntryImpl entry, 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 (traceEnabled) {
        LOG.tracev("Assembling entity from second-level cache: {0}", 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
    final EntityKey entityKey = session.generateEntityKey(id, subclassPersister);
    TwoPhaseLoad.addUninitializedCachedEntity(entityKey, result, subclassPersister, LockMode.NONE, entry.getVersion(), session);
    Type[] types = subclassPersister.getPropertyTypes();
    Object[] values = entry.assemble(result, id, subclassPersister, session.getInterceptor(), session);
    // intializes result by side-effect
    TypeHelper.deepCopy(values, types, subclassPersister.getPropertyUpdateability(), values, session);
    Object version = Versioning.getVersion(values, subclassPersister);
    LOG.tracev("Cached Version: {0}", version);
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    boolean isReadOnly = session.isDefaultReadOnly();
    if (persister.isMutable()) {
        Object proxy = persistenceContext.getProxy(entityKey);
        if (proxy != null) {
            // there is already a proxy for this impl
            // only set the status to read-only if the proxy is read-only
            isReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
        }
    } else {
        isReadOnly = true;
    }
    persistenceContext.addEntry(result, (isReadOnly ? Status.READ_ONLY : Status.MANAGED), values, null, id, version, LockMode.NONE, true, subclassPersister, false);
    subclassPersister.afterInitialize(result, session);
    persistenceContext.initializeNonLazyCollections();
    // upgrade the lock if necessary:
    //lock(result, lockMode);
    //PostLoad is needed for EJB3
    //TODO: reuse the PostLoadEvent...
    PostLoadEvent postLoadEvent = event.getPostLoadEvent().setEntity(result).setId(id).setPersister(persister);
    for (PostLoadEventListener listener : postLoadEventListeners(session)) {
        listener.onPostLoad(postLoadEvent);
    }
    return result;
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) PostLoadEvent(org.hibernate.event.spi.PostLoadEvent) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) StatefulPersistenceContext(org.hibernate.engine.internal.StatefulPersistenceContext) HibernateProxy(org.hibernate.proxy.HibernateProxy) PostLoadEventListener(org.hibernate.event.spi.PostLoadEventListener) EntityKey(org.hibernate.engine.spi.EntityKey) EventSource(org.hibernate.event.spi.EventSource) EmbeddedComponentType(org.hibernate.type.EmbeddedComponentType) EntityType(org.hibernate.type.EntityType) EventType(org.hibernate.event.spi.EventType) Type(org.hibernate.type.Type)

Aggregations

PersistenceContext (org.hibernate.engine.spi.PersistenceContext)31 Serializable (java.io.Serializable)8 EntityEntry (org.hibernate.engine.spi.EntityEntry)8 EntityKey (org.hibernate.engine.spi.EntityKey)7 EventSource (org.hibernate.event.spi.EventSource)7 EntityPersister (org.hibernate.persister.entity.EntityPersister)7 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)6 List (java.util.List)5 PersistentCollection (org.hibernate.collection.spi.PersistentCollection)5 AssertionFailure (org.hibernate.AssertionFailure)4 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)4 Type (org.hibernate.type.Type)4 ArrayList (java.util.ArrayList)3 EntityRegionAccessStrategy (org.hibernate.cache.spi.access.EntityRegionAccessStrategy)3 StatefulPersistenceContext (org.hibernate.engine.internal.StatefulPersistenceContext)3 CollectionEntry (org.hibernate.engine.spi.CollectionEntry)3 EventType (org.hibernate.event.spi.EventType)3 PostLoadEventListener (org.hibernate.event.spi.PostLoadEventListener)3 CollectionPersister (org.hibernate.persister.collection.CollectionPersister)3 HibernateProxy (org.hibernate.proxy.HibernateProxy)3