Search in sources :

Example 11 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class ForeignKeys method isTransient.

/**
	 * Is this instance, which we know is not persistent, actually transient?
	 * <p/>
	 * If <tt>assumed</tt> is non-null, don't hit the database to make the determination, instead assume that
	 * value; the client code must be prepared to "recover" in the case that this assumed result is incorrect.
	 *
	 * @param entityName The name of the entity
	 * @param entity The entity instance
	 * @param assumed The assumed return value, if avoiding database hit is desired
	 * @param session The session
	 *
	 * @return {@code true} if the given entity is transient (unsaved)
	 */
public static boolean isTransient(String entityName, Object entity, Boolean assumed, SharedSessionContractImplementor session) {
    if (entity == LazyPropertyInitializer.UNFETCHED_PROPERTY) {
        // an entity that already exists in the db
        return false;
    }
    // let the interceptor inspect the instance to decide
    Boolean isUnsaved = session.getInterceptor().isTransient(entity);
    if (isUnsaved != null) {
        return isUnsaved;
    }
    // let the persister inspect the instance to decide
    final EntityPersister persister = session.getEntityPersister(entityName, entity);
    isUnsaved = persister.isTransient(entity, session);
    if (isUnsaved != null) {
        return isUnsaved;
    }
    // the database
    if (assumed != null) {
        return assumed;
    }
    // hit the database, afterQuery checking the session cache for a snapshot
    final Object[] snapshot = session.getPersistenceContext().getDatabaseSnapshot(persister.getIdentifier(entity, session), persister);
    return snapshot == null;
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister)

Example 12 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class AbstractLockUpgradeEventListener method upgradeLock.

/**
	 * Performs a pessimistic lock upgrade on a given entity, if needed.
	 *
	 * @param object The entity for which to upgrade the lock.
	 * @param entry The entity's EntityEntry instance.
	 * @param lockOptions contains the requested lock mode.
	 * @param source The session which is the source of the event being processed.
	 */
protected void upgradeLock(Object object, EntityEntry entry, LockOptions lockOptions, EventSource source) {
    LockMode requestedLockMode = lockOptions.getLockMode();
    if (requestedLockMode.greaterThan(entry.getLockMode())) {
        if (entry.getStatus() != Status.MANAGED) {
            throw new ObjectDeletedException("attempted to lock a deleted instance", entry.getId(), entry.getPersister().getEntityName());
        }
        final EntityPersister persister = entry.getPersister();
        if (log.isTraceEnabled()) {
            log.tracev("Locking {0} in mode: {1}", MessageHelper.infoString(persister, entry.getId(), source.getFactory()), requestedLockMode);
        }
        final boolean cachingEnabled = persister.hasCache();
        SoftLock lock = null;
        Object ck = null;
        try {
            if (cachingEnabled) {
                EntityRegionAccessStrategy cache = persister.getCacheAccessStrategy();
                ck = cache.generateCacheKey(entry.getId(), persister, source.getFactory(), source.getTenantIdentifier());
                lock = cache.lockItem(source, ck, entry.getVersion());
            }
            if (persister.isVersioned() && requestedLockMode == LockMode.FORCE) {
                // todo : should we check the current isolation mode explicitly?
                Object nextVersion = persister.forceVersionIncrement(entry.getId(), entry.getVersion(), source);
                entry.forceLocked(object, nextVersion);
            } else {
                persister.lock(entry.getId(), entry.getVersion(), object, lockOptions, source);
            }
            entry.setLockMode(requestedLockMode);
        } finally {
            // so release the soft lock
            if (cachingEnabled) {
                persister.getCacheAccessStrategy().unlockItem(source, ck, lock);
            }
        }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) ObjectDeletedException(org.hibernate.ObjectDeletedException) LockMode(org.hibernate.LockMode) SoftLock(org.hibernate.cache.spi.access.SoftLock)

Example 13 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class AbstractSaveEventListener method saveWithGeneratedId.

/**
	 * Prepares the save call using a newly generated id.
	 *
	 * @param entity The entity to be saved
	 * @param entityName The entity-name for the entity to be saved
	 * @param anything Generally cascade-specific information.
	 * @param source The session which is the source of this save event.
	 * @param requiresImmediateIdAccess does the event context require
	 * access to the identifier immediately afterQuery execution of this method (if
	 * not, post-insert style id generators may be postponed if we are outside
	 * a transaction).
	 *
	 * @return The id used to save the entity; may be null depending on the
	 *         type of id generator used and the requiresImmediateIdAccess value
	 */
protected Serializable saveWithGeneratedId(Object entity, String entityName, Object anything, EventSource source, boolean requiresImmediateIdAccess) {
    if (entity instanceof SelfDirtinessTracker) {
        ((SelfDirtinessTracker) entity).$$_hibernate_clearDirtyAttributes();
    }
    EntityPersister persister = source.getEntityPersister(entityName, entity);
    Serializable generatedId = persister.getIdentifierGenerator().generate(source, entity);
    if (generatedId == null) {
        throw new IdentifierGenerationException("null id generated for:" + entity.getClass());
    } else if (generatedId == IdentifierGeneratorHelper.SHORT_CIRCUIT_INDICATOR) {
        return source.getIdentifier(entity);
    } else if (generatedId == IdentifierGeneratorHelper.POST_INSERT_INDICATOR) {
        return performSave(entity, null, persister, true, anything, source, requiresImmediateIdAccess);
    } else {
        // TODO: define toString()s for generators
        if (LOG.isDebugEnabled()) {
            LOG.debugf("Generated identifier: %s, using strategy: %s", persister.getIdentifierType().toLoggableString(generatedId, source.getFactory()), persister.getIdentifierGenerator().getClass().getName());
        }
        return performSave(entity, generatedId, persister, false, anything, source, true);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) IdentifierGenerationException(org.hibernate.id.IdentifierGenerationException) SelfDirtinessTracker(org.hibernate.engine.spi.SelfDirtinessTracker)

Example 14 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class DefaultDeleteEventListener method onDelete.

/**
	 * Handle the given delete event.  This is the cascaded form.
	 *
	 * @param event The delete event.
	 * @param transientEntities The cache of entities already deleted
	 *
	 * @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;
        }
        performDetachedEntityDeletionCheck(event);
        id = persister.getIdentifier(entity, source);
        if (id == null) {
            throw new TransientObjectException("the detached instance passed to delete() had a null identifier");
        }
        final EntityKey key = source.generateEntityKey(id, persister);
        persistenceContext.checkUniqueness(key, entity);
        new OnUpdateVisitor(source, id, entity).process(entity, persister);
        version = persister.getVersion(entity);
        entityEntry = persistenceContext.addEntity(entity, (persister.isMutable() ? Status.MANAGED : Status.READ_ONLY), persister.getPropertyValues(entity), key, version, LockMode.NONE, true, persister, 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 (invokeDeleteLifecycle(source, entity, persister)) {
        return;
    }
    deleteEntity(source, entity, entityEntry, event.isCascadeDeleteEnabled(), event.isOrphanRemovalBeforeUpdates(), persister, transientEntities);
    if (source.getFactory().getSettings().isIdentifierRollbackEnabled()) {
        persister.resetIdentifier(entity, id, version, source);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) TransientObjectException(org.hibernate.TransientObjectException) EntityKey(org.hibernate.engine.spi.EntityKey) EventSource(org.hibernate.event.spi.EventSource) EntityEntry(org.hibernate.engine.spi.EntityEntry) Serializable(java.io.Serializable) PersistenceContext(org.hibernate.engine.spi.PersistenceContext)

Example 15 with EntityPersister

use of org.hibernate.persister.entity.EntityPersister in project hibernate-orm by hibernate.

the class CollectionLoadContext method addCollectionToCache.

/**
	 * Add the collection to the second-level cache
	 *
	 * @param lce The entry representing the collection to add
	 * @param persister The persister
	 */
private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) {
    final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
    final SessionFactoryImplementor factory = session.getFactory();
    final boolean debugEnabled = LOG.isDebugEnabled();
    if (debugEnabled) {
        LOG.debugf("Caching collection: %s", MessageHelper.collectionInfoString(persister, lce.getCollection(), lce.getKey(), session));
    }
    if (!session.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters(session)) {
        // some filters affecting the collection are enabled on the session, so do not do the put into the cache.
        if (debugEnabled) {
            LOG.debug("Refusing to add to cache due to enabled filters");
        }
        // EARLY EXIT!!!!!
        return;
    }
    final Object version;
    if (persister.isVersioned()) {
        Object collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner(lce.getKey(), persister);
        if (collectionOwner == null) {
            // resolution against the PC anyway just to be safe since the lookup should not be costly.
            if (lce.getCollection() != null) {
                final Object linkedOwner = lce.getCollection().getOwner();
                if (linkedOwner != null) {
                    final Serializable ownerKey = persister.getOwnerEntityPersister().getIdentifier(linkedOwner, session);
                    collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner(ownerKey, persister);
                }
            }
            if (collectionOwner == null) {
                throw new HibernateException("Unable to resolve owner of loading collection [" + MessageHelper.collectionInfoString(persister, lce.getCollection(), lce.getKey(), session) + "] for second level caching");
            }
        }
        version = getLoadContext().getPersistenceContext().getEntry(collectionOwner).getVersion();
    } else {
        version = null;
    }
    final CollectionCacheEntry entry = new CollectionCacheEntry(lce.getCollection(), persister);
    final CollectionRegionAccessStrategy cache = persister.getCacheAccessStrategy();
    final Object cacheKey = cache.generateCacheKey(lce.getKey(), persister, session.getFactory(), session.getTenantIdentifier());
    boolean isPutFromLoad = true;
    if (persister.getElementType().isAssociationType()) {
        for (Serializable id : entry.getState()) {
            EntityPersister entityPersister = ((QueryableCollection) persister).getElementPersister();
            if (session.getPersistenceContext().wasInsertedDuringTransaction(entityPersister, id)) {
                isPutFromLoad = false;
                break;
            }
        }
    }
    // CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad
    if (isPutFromLoad) {
        try {
            session.getEventListenerManager().cachePutStart();
            final boolean put = cache.putFromLoad(session, cacheKey, persister.getCacheEntryStructure().structure(entry), session.getTimestamp(), version, factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode() != CacheMode.REFRESH);
            if (put && factory.getStatistics().isStatisticsEnabled()) {
                factory.getStatistics().secondLevelCachePut(persister.getCacheAccessStrategy().getRegion().getName());
            }
        } finally {
            session.getEventListenerManager().cachePutEnd();
        }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) CollectionCacheEntry(org.hibernate.cache.spi.entry.CollectionCacheEntry) HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) QueryableCollection(org.hibernate.persister.collection.QueryableCollection) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy)

Aggregations

EntityPersister (org.hibernate.persister.entity.EntityPersister)166 Test (org.junit.Test)59 Serializable (java.io.Serializable)34 Session (org.hibernate.Session)31 Type (org.hibernate.type.Type)29 EntityEntry (org.hibernate.engine.spi.EntityEntry)21 EventSource (org.hibernate.event.spi.EventSource)15 EntityRegionAccessStrategy (org.hibernate.cache.spi.access.EntityRegionAccessStrategy)13 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)13 TestForIssue (org.hibernate.testing.TestForIssue)13 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)12 SequenceStyleGenerator (org.hibernate.id.enhanced.SequenceStyleGenerator)12 EntityType (org.hibernate.type.EntityType)12 ArrayList (java.util.ArrayList)11 CompositeType (org.hibernate.type.CompositeType)11 HibernateProxy (org.hibernate.proxy.HibernateProxy)10 PreparedStatement (java.sql.PreparedStatement)8 List (java.util.List)8 EntityKey (org.hibernate.engine.spi.EntityKey)8 QueryParameters (org.hibernate.engine.spi.QueryParameters)8