Search in sources :

Example 26 with AssertionFailure

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

the class StatementPreparerImpl method prepareQueryStatement.

@Override
public PreparedStatement prepareQueryStatement(String sql, final boolean isCallable, final ScrollMode scrollMode) {
    if (scrollMode != null && !scrollMode.equals(ScrollMode.FORWARD_ONLY)) {
        if (!settings().isScrollableResultSetsEnabled()) {
            throw new AssertionFailure("scrollable result sets are not enabled");
        }
        final PreparedStatement ps = new QueryStatementPreparationTemplate(sql) {

            public PreparedStatement doPrepare() throws SQLException {
                return isCallable ? connection().prepareCall(sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY) : connection().prepareStatement(sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY);
            }
        }.prepareStatement();
        jdbcCoordinator.registerLastQuery(ps);
        return ps;
    } else {
        final PreparedStatement ps = new QueryStatementPreparationTemplate(sql) {

            public PreparedStatement doPrepare() throws SQLException {
                return isCallable ? connection().prepareCall(sql) : connection().prepareStatement(sql);
            }
        }.prepareStatement();
        jdbcCoordinator.registerLastQuery(ps);
        return ps;
    }
}
Also used : AssertionFailure(org.hibernate.AssertionFailure) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement)

Example 27 with AssertionFailure

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

the class DefaultSaveOrUpdateEventListener method entityIsDetached.

/**
	 * The given save-update event named a detached entity.
	 * <p/>
	 * Here, we will perform the update processing.
	 *
	 * @param event The update event to be handled.
	 */
protected void entityIsDetached(SaveOrUpdateEvent event) {
    LOG.trace("Updating detached instance");
    if (event.getSession().getPersistenceContext().isEntryFor(event.getEntity())) {
        //TODO: assertion only, could be optimized away
        throw new AssertionFailure("entity was persistent");
    }
    Object entity = event.getEntity();
    EntityPersister persister = event.getSession().getEntityPersister(event.getEntityName(), entity);
    event.setRequestedId(getUpdateId(entity, persister, event.getRequestedId(), event.getSession()));
    performUpdate(event, entity, persister);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) AssertionFailure(org.hibernate.AssertionFailure)

Example 28 with AssertionFailure

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

the class DefaultSaveOrUpdateEventListener method entityIsPersistent.

protected Serializable entityIsPersistent(SaveOrUpdateEvent event) throws HibernateException {
    final boolean traceEnabled = LOG.isTraceEnabled();
    if (traceEnabled) {
        LOG.trace("Ignoring persistent instance");
    }
    EntityEntry entityEntry = event.getEntry();
    if (entityEntry == null) {
        throw new AssertionFailure("entity was transient or detached");
    } else {
        if (entityEntry.getStatus() == Status.DELETED) {
            throw new AssertionFailure("entity was deleted");
        }
        final SessionFactoryImplementor factory = event.getSession().getFactory();
        Serializable requestedId = event.getRequestedId();
        Serializable savedId;
        if (requestedId == null) {
            savedId = entityEntry.getId();
        } else {
            final boolean isEqual = !entityEntry.getPersister().getIdentifierType().isEqual(requestedId, entityEntry.getId(), factory);
            if (isEqual) {
                throw new PersistentObjectException("object passed to save() was already persistent: " + MessageHelper.infoString(entityEntry.getPersister(), requestedId, factory));
            }
            savedId = requestedId;
        }
        if (traceEnabled) {
            LOG.tracev("Object already associated with session: {0}", MessageHelper.infoString(entityEntry.getPersister(), savedId, factory));
        }
        return savedId;
    }
}
Also used : EntityEntry(org.hibernate.engine.spi.EntityEntry) Serializable(java.io.Serializable) AssertionFailure(org.hibernate.AssertionFailure) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistentObjectException(org.hibernate.PersistentObjectException)

Example 29 with AssertionFailure

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

the class Loader method sequentialLoad.

private Object sequentialLoad(final ResultSet resultSet, final SharedSessionContractImplementor session, final QueryParameters queryParameters, final boolean returnProxies, final EntityKey keyToRead) throws HibernateException {
    final int entitySpan = getEntityPersisters().length;
    final List hydratedObjects = entitySpan == 0 ? null : new ArrayList(entitySpan);
    Object result = null;
    final EntityKey[] loadedKeys = new EntityKey[entitySpan];
    try {
        do {
            Object loaded = getRowFromResultSet(resultSet, session, queryParameters, getLockModes(queryParameters.getLockOptions()), null, hydratedObjects, loadedKeys, returnProxies);
            if (!keyToRead.equals(loadedKeys[0])) {
                throw new AssertionFailure(String.format("Unexpected key read for row; expected [%s]; actual [%s]", keyToRead, loadedKeys[0]));
            }
            if (result == null) {
                result = loaded;
            }
        } while (resultSet.next() && isCurrentRowForSameEntity(keyToRead, 0, resultSet, session));
    } catch (SQLException sqle) {
        throw factory.getJdbcServices().getSqlExceptionHelper().convert(sqle, "could not doAfterTransactionCompletion sequential read of results (forward)", getSQLString());
    }
    initializeEntitiesAndCollections(hydratedObjects, resultSet, session, queryParameters.isReadOnly(session));
    session.getPersistenceContext().initializeNonLazyCollections();
    return result;
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) AssertionFailure(org.hibernate.AssertionFailure) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList)

Example 30 with AssertionFailure

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

the class EntityUpdateAction method execute.

@Override
public void execute() throws HibernateException {
    final Serializable id = getId();
    final EntityPersister persister = getPersister();
    final SharedSessionContractImplementor session = getSession();
    final Object instance = getInstance();
    final boolean veto = preUpdate();
    final SessionFactoryImplementor factory = session.getFactory();
    Object previousVersion = this.previousVersion;
    if (persister.isVersionPropertyGenerated()) {
        // we need to grab the version value from the entity, otherwise
        // we have issues with generated-version entities that may have
        // multiple actions queued during the same flush
        previousVersion = persister.getVersion(instance);
    }
    final Object ck;
    if (persister.hasCache()) {
        final EntityRegionAccessStrategy cache = persister.getCacheAccessStrategy();
        ck = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
        lock = cache.lockItem(session, ck, previousVersion);
    } else {
        ck = null;
    }
    if (!veto) {
        persister.update(id, state, dirtyFields, hasDirtyCollection, previousState, previousVersion, instance, rowId, session);
    }
    final EntityEntry entry = session.getPersistenceContext().getEntry(instance);
    if (entry == null) {
        throw new AssertionFailure("possible nonthreadsafe access to session");
    }
    if (entry.getStatus() == Status.MANAGED || persister.isVersionPropertyGenerated()) {
        // get the updated snapshot of the entity state by cloning current state;
        // it is safe to copy in place, since by this time no-one else (should have)
        // has a reference  to the array
        TypeHelper.deepCopy(state, persister.getPropertyTypes(), persister.getPropertyCheckability(), state, session);
        if (persister.hasUpdateGeneratedProperties()) {
            // this entity defines proeprty generation, so process those generated
            // values...
            persister.processUpdateGeneratedProperties(id, instance, state, session);
            if (persister.isVersionPropertyGenerated()) {
                nextVersion = Versioning.getVersion(state, persister);
            }
        }
        // have the entity entry doAfterTransactionCompletion post-update processing, passing it the
        // update state and the new version (if one).
        entry.postUpdate(instance, state, nextVersion);
    }
    if (persister.hasCache()) {
        if (persister.isCacheInvalidationRequired() || entry.getStatus() != Status.MANAGED) {
            persister.getCacheAccessStrategy().remove(session, ck);
        } else if (session.getCacheMode().isPutEnabled()) {
            //TODO: inefficient if that cache is just going to ignore the updated state!
            final CacheEntry ce = persister.buildCacheEntry(instance, state, nextVersion, getSession());
            cacheEntry = persister.getCacheEntryStructure().structure(ce);
            final boolean put = cacheUpdate(persister, previousVersion, ck);
            if (put && factory.getStatistics().isStatisticsEnabled()) {
                factory.getStatistics().secondLevelCachePut(getPersister().getCacheAccessStrategy().getRegion().getName());
            }
        }
    }
    session.getPersistenceContext().getNaturalIdHelper().manageSharedNaturalIdCrossReference(persister, id, state, previousNaturalIdValues, CachedNaturalIdValueSource.UPDATE);
    postUpdate();
    if (factory.getStatistics().isStatisticsEnabled() && !veto) {
        factory.getStatistics().updateEntity(getPersister().getEntityName());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) EntityEntry(org.hibernate.engine.spi.EntityEntry) AssertionFailure(org.hibernate.AssertionFailure) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry)

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