Search in sources :

Example 41 with EntityPersister

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

the class PessimisticForceIncrementLockingStrategy method lock.

@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
    if (!lockable.isVersioned()) {
        throw new HibernateException("[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]");
    }
    final EntityEntry entry = session.getPersistenceContext().getEntry(object);
    final EntityPersister persister = entry.getPersister();
    final Object nextVersion = persister.forceVersionIncrement(entry.getId(), entry.getVersion(), session);
    entry.forceLocked(object, nextVersion);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityEntry(org.hibernate.engine.spi.EntityEntry) HibernateException(org.hibernate.HibernateException)

Example 42 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 43 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 44 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 45 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)

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