Search in sources :

Example 31 with SessionFactoryImplementor

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

the class TwoPhaseLoad method doInitializeEntity.

private static void doInitializeEntity(final Object entity, final EntityEntry entityEntry, final boolean readOnly, final SharedSessionContractImplementor session, final PreLoadEvent preLoadEvent) throws HibernateException {
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    final EntityPersister persister = entityEntry.getPersister();
    final Serializable id = entityEntry.getId();
    final Object[] hydratedState = entityEntry.getLoadedState();
    final boolean debugEnabled = LOG.isDebugEnabled();
    if (debugEnabled) {
        LOG.debugf("Resolving associations for %s", MessageHelper.infoString(persister, id, session.getFactory()));
    }
    final Type[] types = persister.getPropertyTypes();
    for (int i = 0; i < hydratedState.length; i++) {
        final Object value = hydratedState[i];
        if (value == LazyPropertyInitializer.UNFETCHED_PROPERTY) {
            // No resolution is necessary, unless the lazy property is a collection.
            if (types[i].isCollectionType()) {
                // IMPLEMENTATION NOTE: this is a lazy collection property on a bytecode-enhanced entity.
                // HHH-10989: We need to resolve the collection so that a CollectionReference is added to StatefulPersistentContext.
                // As mentioned above, hydratedState[i] needs to remain LazyPropertyInitializer.UNFETCHED_PROPERTY
                // so do not assign the resolved, unitialized PersistentCollection back to hydratedState[i].
                types[i].resolve(value, session, entity);
            }
        } else if (value != PropertyAccessStrategyBackRefImpl.UNKNOWN) {
            // we know value != LazyPropertyInitializer.UNFETCHED_PROPERTY
            hydratedState[i] = types[i].resolve(value, session, entity);
        }
    }
    //Must occur afterQuery resolving identifiers!
    if (session.isEventSource()) {
        preLoadEvent.setEntity(entity).setState(hydratedState).setId(id).setPersister(persister);
        final EventListenerGroup<PreLoadEventListener> listenerGroup = session.getFactory().getServiceRegistry().getService(EventListenerRegistry.class).getEventListenerGroup(EventType.PRE_LOAD);
        for (PreLoadEventListener listener : listenerGroup.listeners()) {
            listener.onPreLoad(preLoadEvent);
        }
    }
    persister.setPropertyValues(entity, hydratedState);
    final SessionFactoryImplementor factory = session.getFactory();
    if (persister.hasCache() && session.getCacheMode().isPutEnabled()) {
        if (debugEnabled) {
            LOG.debugf("Adding entity to second-level cache: %s", MessageHelper.infoString(persister, id, session.getFactory()));
        }
        final Object version = Versioning.getVersion(hydratedState, persister);
        final CacheEntry entry = persister.buildCacheEntry(entity, hydratedState, version, session);
        final EntityRegionAccessStrategy cache = persister.getCacheAccessStrategy();
        final Object cacheKey = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
        // we need to be careful not to clobber the lock here in the cache so that it can be rolled back if need be
        if (session.getPersistenceContext().wasInsertedDuringTransaction(persister, id)) {
            cache.update(session, cacheKey, persister.getCacheEntryStructure().structure(entry), version, version);
        } else {
            final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
            try {
                eventListenerManager.cachePutStart();
                final boolean put = cache.putFromLoad(session, cacheKey, persister.getCacheEntryStructure().structure(entry), session.getTimestamp(), version, useMinimalPuts(session, entityEntry));
                if (put && factory.getStatistics().isStatisticsEnabled()) {
                    factory.getStatistics().secondLevelCachePut(cache.getRegion().getName());
                }
            } finally {
                eventListenerManager.cachePutEnd();
            }
        }
    }
    if (persister.hasNaturalIdentifier()) {
        persistenceContext.getNaturalIdHelper().cacheNaturalIdCrossReferenceFromLoad(persister, id, persistenceContext.getNaturalIdHelper().extractNaturalIdValues(hydratedState, persister));
    }
    boolean isReallyReadOnly = readOnly;
    if (!persister.isMutable()) {
        isReallyReadOnly = true;
    } else {
        final Object proxy = persistenceContext.getProxy(entityEntry.getEntityKey());
        if (proxy != null) {
            // there is already a proxy for this impl
            // only set the status to read-only if the proxy is read-only
            isReallyReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
        }
    }
    if (isReallyReadOnly) {
        //no need to take a snapshot - this is a
        //performance optimization, but not really
        //important, except for entities with huge
        //mutable property values
        persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY);
    } else {
        //take a snapshot
        TypeHelper.deepCopy(hydratedState, persister.getPropertyTypes(), persister.getPropertyUpdateability(), //afterQuery setting values to object
        hydratedState, session);
        persistenceContext.setEntryStatus(entityEntry, Status.MANAGED);
    }
    persister.afterInitialize(entity, session);
    if (debugEnabled) {
        LOG.debugf("Done materializing entity %s", MessageHelper.infoString(persister, id, session.getFactory()));
    }
    if (factory.getStatistics().isStatisticsEnabled()) {
        factory.getStatistics().loadEntity(persister.getEntityName());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityRegionAccessStrategy(org.hibernate.cache.spi.access.EntityRegionAccessStrategy) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) PreLoadEventListener(org.hibernate.event.spi.PreLoadEventListener) CacheEntry(org.hibernate.cache.spi.entry.CacheEntry) HibernateProxy(org.hibernate.proxy.HibernateProxy) EventListenerRegistry(org.hibernate.event.service.spi.EventListenerRegistry) EventType(org.hibernate.event.spi.EventType) Type(org.hibernate.type.Type) SessionEventListenerManager(org.hibernate.engine.spi.SessionEventListenerManager)

Example 32 with SessionFactoryImplementor

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

the class SubqueryExpression method getTypedValues.

@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    //the following two lines were added to ensure that this.params is not null, which
    //can happen with two-deep nested subqueries
    final SessionFactoryImplementor factory = criteriaQuery.getFactory();
    createAndSetInnerQuery(criteriaQuery, factory);
    final Type[] ppTypes = params.getPositionalParameterTypes();
    final Object[] ppValues = params.getPositionalParameterValues();
    final TypedValue[] tv = new TypedValue[ppTypes.length];
    for (int i = 0; i < ppTypes.length; i++) {
        tv[i] = new TypedValue(ppTypes[i], ppValues[i]);
    }
    return tv;
}
Also used : Type(org.hibernate.type.Type) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) TypedValue(org.hibernate.engine.spi.TypedValue)

Example 33 with SessionFactoryImplementor

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

the class PessimisticReadSelectLockingStrategy method generateLockString.

protected String generateLockString(int lockTimeout) {
    final SessionFactoryImplementor factory = getLockable().getFactory();
    final LockOptions lockOptions = new LockOptions(getLockMode());
    lockOptions.setTimeOut(lockTimeout);
    final SimpleSelect select = new SimpleSelect(factory.getDialect()).setLockOptions(lockOptions).setTableName(getLockable().getRootTableName()).addColumn(getLockable().getRootTableIdentifierColumnNames()[0]).addCondition(getLockable().getRootTableIdentifierColumnNames(), "=?");
    if (getLockable().isVersioned()) {
        select.addCondition(getLockable().getVersionColumnName(), "=?");
    }
    if (factory.getSessionFactoryOptions().isCommentsEnabled()) {
        select.setComment(getLockMode() + " lock " + getLockable().getEntityName());
    }
    return select.toStatementString();
}
Also used : LockOptions(org.hibernate.LockOptions) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SimpleSelect(org.hibernate.sql.SimpleSelect)

Example 34 with SessionFactoryImplementor

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

the class PessimisticReadUpdateLockingStrategy method lock.

@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
    if (!lockable.isVersioned()) {
        throw new HibernateException("write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]");
    }
    final SessionFactoryImplementor factory = session.getFactory();
    try {
        try {
            final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql);
            try {
                lockable.getVersionType().nullSafeSet(st, version, 1, session);
                int offset = 2;
                lockable.getIdentifierType().nullSafeSet(st, id, offset, session);
                offset += lockable.getIdentifierType().getColumnSpan(factory);
                if (lockable.isVersioned()) {
                    lockable.getVersionType().nullSafeSet(st, version, offset, session);
                }
                final int affected = session.getJdbcCoordinator().getResultSetReturn().executeUpdate(st);
                // todo:  should this instead check for exactly one row modified?
                if (affected < 0) {
                    if (factory.getStatistics().isStatisticsEnabled()) {
                        factory.getStatistics().optimisticFailure(lockable.getEntityName());
                    }
                    throw new StaleObjectStateException(lockable.getEntityName(), id);
                }
            } finally {
                session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(st);
                session.getJdbcCoordinator().afterStatementExecution();
            }
        } catch (SQLException e) {
            throw session.getJdbcServices().getSqlExceptionHelper().convert(e, "could not lock: " + MessageHelper.infoString(lockable, id, session.getFactory()), sql);
        }
    } catch (JDBCException e) {
        throw new PessimisticEntityLockException(object, "could not obtain pessimistic lock", e);
    }
}
Also used : JDBCException(org.hibernate.JDBCException) HibernateException(org.hibernate.HibernateException) SQLException(java.sql.SQLException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PreparedStatement(java.sql.PreparedStatement) StaleObjectStateException(org.hibernate.StaleObjectStateException)

Example 35 with SessionFactoryImplementor

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

the class PessimisticWriteSelectLockingStrategy method lock.

@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
    final String sql = determineSql(timeout);
    final SessionFactoryImplementor factory = session.getFactory();
    try {
        try {
            final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql);
            try {
                getLockable().getIdentifierType().nullSafeSet(st, id, 1, session);
                if (getLockable().isVersioned()) {
                    getLockable().getVersionType().nullSafeSet(st, version, getLockable().getIdentifierType().getColumnSpan(factory) + 1, session);
                }
                final ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract(st);
                try {
                    if (!rs.next()) {
                        if (factory.getStatistics().isStatisticsEnabled()) {
                            factory.getStatistics().optimisticFailure(getLockable().getEntityName());
                        }
                        throw new StaleObjectStateException(getLockable().getEntityName(), id);
                    }
                } finally {
                    session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(rs, st);
                }
            } finally {
                session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(st);
                session.getJdbcCoordinator().afterStatementExecution();
            }
        } catch (SQLException e) {
            throw session.getJdbcServices().getSqlExceptionHelper().convert(e, "could not lock: " + MessageHelper.infoString(getLockable(), id, session.getFactory()), sql);
        }
    } catch (JDBCException e) {
        throw new PessimisticEntityLockException(object, "could not obtain pessimistic lock", e);
    }
}
Also used : JDBCException(org.hibernate.JDBCException) SQLException(java.sql.SQLException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) StaleObjectStateException(org.hibernate.StaleObjectStateException)

Aggregations

SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)129 Test (org.junit.Test)46 Configuration (org.hibernate.cfg.Configuration)27 SQLException (java.sql.SQLException)18 Type (org.hibernate.type.Type)16 EntityPersister (org.hibernate.persister.entity.EntityPersister)13 Connection (java.sql.Connection)12 HibernateException (org.hibernate.HibernateException)12 PreparedStatement (java.sql.PreparedStatement)11 Metadata (org.hibernate.boot.Metadata)11 Statement (java.sql.Statement)10 ArrayList (java.util.ArrayList)10 JdbcConnectionAccess (org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess)10 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)10 Serializable (java.io.Serializable)9 EncapsulatedCompositeIdResultSetProcessorTest (org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)8 HashMap (java.util.HashMap)7 Integrator (org.hibernate.integrator.spi.Integrator)7 SessionFactoryServiceRegistry (org.hibernate.service.spi.SessionFactoryServiceRegistry)7 Map (java.util.Map)6