Search in sources :

Example 16 with AssertionFailure

use of org.hibernate.AssertionFailure in project hibernate-orm by hibernate.

the class DefaultFlushEntityEventListener method scheduleUpdate.

private boolean scheduleUpdate(final FlushEntityEvent event) {
    final EntityEntry entry = event.getEntityEntry();
    final EventSource session = event.getSession();
    final Object entity = event.getEntity();
    final Status status = entry.getStatus();
    final EntityPersister persister = entry.getPersister();
    final Object[] values = event.getPropertyValues();
    if (LOG.isTraceEnabled()) {
        if (status == Status.DELETED) {
            if (!persister.isMutable()) {
                LOG.tracev("Updating immutable, deleted entity: {0}", MessageHelper.infoString(persister, entry.getId(), session.getFactory()));
            } else if (!entry.isModifiableEntity()) {
                LOG.tracev("Updating non-modifiable, deleted entity: {0}", MessageHelper.infoString(persister, entry.getId(), session.getFactory()));
            } else {
                LOG.tracev("Updating deleted entity: ", MessageHelper.infoString(persister, entry.getId(), session.getFactory()));
            }
        } else {
            LOG.tracev("Updating entity: {0}", MessageHelper.infoString(persister, entry.getId(), session.getFactory()));
        }
    }
    final boolean intercepted = !entry.isBeingReplicated() && handleInterception(event);
    // increment the version number (if necessary)
    final Object nextVersion = getNextVersion(event);
    // if it was dirtied by a collection only
    int[] dirtyProperties = event.getDirtyProperties();
    if (event.isDirtyCheckPossible() && dirtyProperties == null) {
        if (!intercepted && !event.hasDirtyCollection()) {
            throw new AssertionFailure("dirty, but no dirty properties");
        }
        dirtyProperties = ArrayHelper.EMPTY_INT_ARRAY;
    }
    // check nullability but do not doAfterTransactionCompletion command execute
    // we'll use scheduled updates for that.
    new Nullability(session).checkNullability(values, persister, true);
    // schedule the update
    // note that we intentionally do _not_ pass in currentPersistentState!
    session.getActionQueue().addAction(new EntityUpdateAction(entry.getId(), values, dirtyProperties, event.hasDirtyCollection(), (status == Status.DELETED && !entry.isModifiableEntity() ? persister.getPropertyValues(entity) : entry.getLoadedState()), entry.getVersion(), nextVersion, entity, entry.getRowId(), persister, session));
    return intercepted;
}
Also used : Status(org.hibernate.engine.spi.Status) EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityEntry(org.hibernate.engine.spi.EntityEntry) EventSource(org.hibernate.event.spi.EventSource) AssertionFailure(org.hibernate.AssertionFailure) EntityUpdateAction(org.hibernate.action.internal.EntityUpdateAction) Nullability(org.hibernate.engine.internal.Nullability)

Example 17 with AssertionFailure

use of org.hibernate.AssertionFailure in project hibernate-orm by hibernate.

the class DefaultPostLoadEventListener method onPostLoad.

@Override
public void onPostLoad(PostLoadEvent event) {
    final Object entity = event.getEntity();
    final EntityEntry entry = event.getSession().getPersistenceContext().getEntry(entity);
    if (entry == null) {
        throw new AssertionFailure("possible non-threadsafe access to the session");
    }
    final LockMode lockMode = entry.getLockMode();
    if (LockMode.PESSIMISTIC_FORCE_INCREMENT.equals(lockMode)) {
        final EntityPersister persister = entry.getPersister();
        final Object nextVersion = persister.forceVersionIncrement(entry.getId(), entry.getVersion(), event.getSession());
        entry.forceLocked(entity, nextVersion);
    } else if (LockMode.OPTIMISTIC_FORCE_INCREMENT.equals(lockMode)) {
        final EntityIncrementVersionProcess incrementVersion = new EntityIncrementVersionProcess(entity, entry);
        event.getSession().getActionQueue().registerProcess(incrementVersion);
    } else if (LockMode.OPTIMISTIC.equals(lockMode)) {
        final EntityVerifyVersionProcess verifyVersion = new EntityVerifyVersionProcess(entity, entry);
        event.getSession().getActionQueue().registerProcess(verifyVersion);
    }
    if (event.getPersister().implementsLifecycle()) {
        //log.debug( "calling onLoad()" );
        ((Lifecycle) event.getEntity()).onLoad(event.getSession(), event.getId());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityEntry(org.hibernate.engine.spi.EntityEntry) AssertionFailure(org.hibernate.AssertionFailure) EntityVerifyVersionProcess(org.hibernate.action.internal.EntityVerifyVersionProcess) Lifecycle(org.hibernate.classic.Lifecycle) LockMode(org.hibernate.LockMode) EntityIncrementVersionProcess(org.hibernate.action.internal.EntityIncrementVersionProcess)

Example 18 with AssertionFailure

use of org.hibernate.AssertionFailure in project hibernate-orm by hibernate.

the class DefaultMergeEventListener method entityIsDetached.

protected void entityIsDetached(MergeEvent event, Map copyCache) {
    LOG.trace("Merging detached instance");
    final Object entity = event.getEntity();
    final EventSource source = event.getSession();
    final EntityPersister persister = source.getEntityPersister(event.getEntityName(), entity);
    final String entityName = persister.getEntityName();
    Serializable id = event.getRequestedId();
    if (id == null) {
        id = persister.getIdentifier(entity, source);
    } else {
        // check that entity id = requestedId
        Serializable entityId = persister.getIdentifier(entity, source);
        if (!persister.getIdentifierType().isEqual(id, entityId, source.getFactory())) {
            throw new HibernateException("merge requested with id not matching id of passed entity");
        }
    }
    String previousFetchProfile = source.getLoadQueryInfluencers().getInternalFetchProfile();
    source.getLoadQueryInfluencers().setInternalFetchProfile("merge");
    //we must clone embedded composite identifiers, or
    //we will get back the same instance that we pass in
    final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType().deepCopy(id, source.getFactory());
    final Object result = source.get(entityName, clonedIdentifier);
    source.getLoadQueryInfluencers().setInternalFetchProfile(previousFetchProfile);
    if (result == null) {
        //TODO: we should throw an exception if we really *know* for sure
        //      that this is a detached instance, rather than just assuming
        //throw new StaleObjectStateException(entityName, id);
        // we got here because we assumed that an instance
        // with an assigned id was detached, when it was
        // really persistent
        entityIsTransient(event, copyCache);
    } else {
        //beforeQuery cascade!
        ((MergeContext) copyCache).put(entity, result, true);
        final Object target = source.getPersistenceContext().unproxy(result);
        if (target == entity) {
            throw new AssertionFailure("entity was not detached");
        } else if (!source.getEntityName(target).equals(entityName)) {
            throw new WrongClassException("class of the given object did not match class of persistent copy", event.getRequestedId(), entityName);
        } else if (isVersionChanged(entity, source, persister, target)) {
            if (source.getFactory().getStatistics().isStatisticsEnabled()) {
                source.getFactory().getStatisticsImplementor().optimisticFailure(entityName);
            }
            throw new StaleObjectStateException(entityName, id);
        }
        // cascade first, so that all unsaved objects get their
        // copy created beforeQuery we actually copy
        cascadeOnMerge(source, persister, entity, copyCache);
        copyValues(persister, entity, target, source, copyCache);
        //copyValues works by reflection, so explicitly mark the entity instance dirty
        markInterceptorDirty(entity, target, persister);
        event.setResult(result);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EventSource(org.hibernate.event.spi.EventSource) Serializable(java.io.Serializable) AssertionFailure(org.hibernate.AssertionFailure) HibernateException(org.hibernate.HibernateException) WrongClassException(org.hibernate.WrongClassException) StaleObjectStateException(org.hibernate.StaleObjectStateException)

Example 19 with AssertionFailure

use of org.hibernate.AssertionFailure in project hibernate-orm by hibernate.

the class DefaultSaveOrUpdateEventListener method entityIsTransient.

/**
	 * The given save-update event named a transient entity.
	 * <p/>
	 * Here, we will perform the save processing.
	 *
	 * @param event The save event to be handled.
	 *
	 * @return The entity's identifier afterQuery saving.
	 */
protected Serializable entityIsTransient(SaveOrUpdateEvent event) {
    LOG.trace("Saving transient instance");
    final EventSource source = event.getSession();
    EntityEntry entityEntry = event.getEntry();
    if (entityEntry != null) {
        if (entityEntry.getStatus() == Status.DELETED) {
            source.forceFlush(entityEntry);
        } else {
            throw new AssertionFailure("entity was persistent");
        }
    }
    Serializable id = saveWithGeneratedOrRequestedId(event);
    source.getPersistenceContext().reassociateProxy(event.getObject(), id);
    return id;
}
Also used : EventSource(org.hibernate.event.spi.EventSource) EntityEntry(org.hibernate.engine.spi.EntityEntry) Serializable(java.io.Serializable) AssertionFailure(org.hibernate.AssertionFailure)

Example 20 with AssertionFailure

use of org.hibernate.AssertionFailure in project hibernate-orm by hibernate.

the class AbstractSharedSessionContract method resultClassChecking.

@SuppressWarnings({ "unchecked", "WeakerAccess" })
protected void resultClassChecking(Class resultType, NamedSQLQueryDefinition namedQueryDefinition) {
    final NativeSQLQueryReturn[] queryReturns;
    if (namedQueryDefinition.getQueryReturns() != null) {
        queryReturns = namedQueryDefinition.getQueryReturns();
    } else if (namedQueryDefinition.getResultSetRef() != null) {
        final ResultSetMappingDefinition rsMapping = getFactory().getNamedQueryRepository().getResultSetMappingDefinition(namedQueryDefinition.getResultSetRef());
        queryReturns = rsMapping.getQueryReturns();
    } else {
        throw new AssertionFailure("Unsupported named query model. Please report the bug in Hibernate EntityManager");
    }
    if (queryReturns.length > 1) {
        throw new IllegalArgumentException("Cannot create TypedQuery for query with more than one return");
    }
    final NativeSQLQueryReturn nativeSQLQueryReturn = queryReturns[0];
    if (nativeSQLQueryReturn instanceof NativeSQLQueryRootReturn) {
        final Class<?> actualReturnedClass;
        final String entityClassName = ((NativeSQLQueryRootReturn) nativeSQLQueryReturn).getReturnEntityName();
        try {
            actualReturnedClass = getFactory().getServiceRegistry().getService(ClassLoaderService.class).classForName(entityClassName);
        } catch (ClassLoadingException e) {
            throw new AssertionFailure("Unable to load class [" + entityClassName + "] declared on named native query [" + namedQueryDefinition.getName() + "]");
        }
        if (!resultType.isAssignableFrom(actualReturnedClass)) {
            throw buildIncompatibleException(resultType, actualReturnedClass);
        }
    } else if (nativeSQLQueryReturn instanceof NativeSQLQueryConstructorReturn) {
        final NativeSQLQueryConstructorReturn ctorRtn = (NativeSQLQueryConstructorReturn) nativeSQLQueryReturn;
        if (!resultType.isAssignableFrom(ctorRtn.getTargetClass())) {
            throw buildIncompatibleException(resultType, ctorRtn.getTargetClass());
        }
    } else {
        log.debugf("Skiping unhandled NativeSQLQueryReturn type : " + nativeSQLQueryReturn);
    }
}
Also used : AssertionFailure(org.hibernate.AssertionFailure) NativeSQLQueryConstructorReturn(org.hibernate.engine.query.spi.sql.NativeSQLQueryConstructorReturn) NativeSQLQueryReturn(org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) NativeSQLQueryRootReturn(org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn) ResultSetMappingDefinition(org.hibernate.engine.ResultSetMappingDefinition)

Aggregations

AssertionFailure (org.hibernate.AssertionFailure)54 EntityEntry (org.hibernate.engine.spi.EntityEntry)11 Serializable (java.io.Serializable)10 Property (org.hibernate.mapping.Property)10 AnnotationException (org.hibernate.AnnotationException)8 PersistentClass (org.hibernate.mapping.PersistentClass)7 EntityPersister (org.hibernate.persister.entity.EntityPersister)7 SQLException (java.sql.SQLException)6 HibernateException (org.hibernate.HibernateException)6 SimpleValue (org.hibernate.mapping.SimpleValue)6 PreparedStatement (java.sql.PreparedStatement)5 HashMap (java.util.HashMap)5 Component (org.hibernate.mapping.Component)5 Join (org.hibernate.mapping.Join)5 SyntheticProperty (org.hibernate.mapping.SyntheticProperty)5 Iterator (java.util.Iterator)4 EntityRegionAccessStrategy (org.hibernate.cache.spi.access.EntityRegionAccessStrategy)4 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)4 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)4 ManyToOne (org.hibernate.mapping.ManyToOne)4