Search in sources :

Example 36 with SharedSessionContractImplementor

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

the class DefaultRefreshEventListener method evictCachedCollections.

private void evictCachedCollections(Type[] types, Serializable id, EventSource source) throws HibernateException {
    for (Type type : types) {
        if (type.isCollectionType()) {
            CollectionPersister collectionPersister = source.getFactory().getMetamodel().collectionPersister(((CollectionType) type).getRole());
            if (collectionPersister.hasCache()) {
                final CollectionRegionAccessStrategy cache = collectionPersister.getCacheAccessStrategy();
                final Object ck = cache.generateCacheKey(id, collectionPersister, source.getFactory(), source.getTenantIdentifier());
                final SoftLock lock = cache.lockItem(source, ck, null);
                source.getActionQueue().registerProcess(new AfterTransactionCompletionProcess() {

                    @Override
                    public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) {
                        cache.unlockItem(session, ck, lock);
                    }
                });
                cache.remove(source, ck);
            }
        } else if (type.isComponentType()) {
            CompositeType actype = (CompositeType) type;
            evictCachedCollections(actype.getSubtypes(), id, source);
        }
    }
}
Also used : CollectionType(org.hibernate.type.CollectionType) CompositeType(org.hibernate.type.CompositeType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) AfterTransactionCompletionProcess(org.hibernate.action.spi.AfterTransactionCompletionProcess) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy) SoftLock(org.hibernate.cache.spi.access.SoftLock) CompositeType(org.hibernate.type.CompositeType)

Example 37 with SharedSessionContractImplementor

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

the class CollectionLoadContext method endLoadingCollections.

/**
	 * Finish the process of collection-loading for this bound result set.  Mainly this
	 * involves cleaning up resources and notifying the collections that loading is
	 * complete.
	 *
	 * @param persister The persister for which to complete loading.
	 */
public void endLoadingCollections(CollectionPersister persister) {
    final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
    if (!loadContexts.hasLoadingCollectionEntries() && localLoadingCollectionKeys.isEmpty()) {
        return;
    }
    // in an effort to avoid concurrent-modification-exceptions (from
    // potential recursive calls back through here as a result of the
    // eventual call to PersistentCollection#endRead), we scan the
    // internal loadingCollections map for matches and store those matches
    // in a temp collection.  the temp collection is then used to "drive"
    // the #endRead processing.
    List<LoadingCollectionEntry> matches = null;
    final Iterator itr = localLoadingCollectionKeys.iterator();
    while (itr.hasNext()) {
        final CollectionKey collectionKey = (CollectionKey) itr.next();
        final LoadingCollectionEntry lce = loadContexts.locateLoadingCollectionEntry(collectionKey);
        if (lce == null) {
            LOG.loadingCollectionKeyNotFound(collectionKey);
        } else if (lce.getResultSet() == resultSet && lce.getPersister() == persister) {
            if (matches == null) {
                matches = new ArrayList<>();
            }
            matches.add(lce);
            if (lce.getCollection().getOwner() == null) {
                session.getPersistenceContext().addUnownedCollection(new CollectionKey(persister, lce.getKey(), persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode()), lce.getCollection());
            }
            LOG.tracev("Removing collection load entry [{0}]", lce);
            // todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)...
            loadContexts.unregisterLoadingCollectionXRef(collectionKey);
            itr.remove();
        }
    }
    endLoadingCollections(persister, matches);
    if (localLoadingCollectionKeys.isEmpty()) {
        // todo : hack!!!
        // NOTE : here we cleanup the load context when we have no more local
        // LCE entries.  This "works" for the time being because really
        // only the collection load contexts are implemented.  Long term,
        // this cleanup should become part of the "close result set"
        // processing from the (sandbox/jdbc) jdbc-container code.
        loadContexts.cleanup(resultSet);
    }
}
Also used : Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CollectionKey(org.hibernate.engine.spi.CollectionKey)

Example 38 with SharedSessionContractImplementor

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

the class CollectionLoadContext method endLoadingCollection.

private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) {
    LOG.tracev("Ending loading collection [{0}]", lce);
    final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
    // warning: can cause a recursive calls! (proxy initialization)
    final boolean hasNoQueuedAdds = lce.getCollection().endRead();
    if (persister.getCollectionType().hasHolder()) {
        getLoadContext().getPersistenceContext().addCollectionHolder(lce.getCollection());
    }
    CollectionEntry ce = getLoadContext().getPersistenceContext().getCollectionEntry(lce.getCollection());
    if (ce == null) {
        ce = getLoadContext().getPersistenceContext().addInitializedCollection(persister, lce.getCollection(), lce.getKey());
    } else {
        ce.postInitialize(lce.getCollection());
    //			if (ce.getLoadedPersister().getBatchSize() > 1) { // not the best place for doing this, moved into ce.postInitialize
    //				getLoadContext().getPersistenceContext().getBatchFetchQueue().removeBatchLoadableCollection(ce); 
    //			}
    }
    // add to cache if:
    boolean addToCache = // there were no queued additions
    hasNoQueuedAdds && // and the role has a cache
    persister.hasCache() && // and this is not a forced initialization during flush
    session.getCacheMode().isPutEnabled() && !ce.isDoremove();
    if (addToCache) {
        addCollectionToCache(lce, persister);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debugf("Collection fully initialized: %s", MessageHelper.collectionInfoString(persister, lce.getCollection(), lce.getKey(), session));
    }
    if (session.getFactory().getStatistics().isStatisticsEnabled()) {
        session.getFactory().getStatistics().loadCollection(persister.getRole());
    }
}
Also used : CollectionEntry(org.hibernate.engine.spi.CollectionEntry) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor)

Example 39 with SharedSessionContractImplementor

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

the class CriteriaLoader method applyLocks.

@Override
protected String applyLocks(String sql, QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) throws QueryException {
    final LockOptions lockOptions = parameters.getLockOptions();
    if (lockOptions == null || (lockOptions.getLockMode() == LockMode.NONE && (lockOptions.getAliasLockCount() == 0 || (lockOptions.getAliasLockCount() == 1 && lockOptions.getAliasSpecificLockMode("this_") == LockMode.NONE)))) {
        return sql;
    }
    if ((parameters.getLockOptions().getFollowOnLocking() == null && dialect.useFollowOnLocking(parameters)) || (parameters.getLockOptions().getFollowOnLocking() != null && parameters.getLockOptions().getFollowOnLocking())) {
        final LockMode lockMode = determineFollowOnLockMode(lockOptions);
        if (lockMode != LockMode.UPGRADE_SKIPLOCKED) {
            // Dialect prefers to perform locking in a separate step
            LOG.usingFollowOnLocking();
            final LockOptions lockOptionsToUse = new LockOptions(lockMode);
            lockOptionsToUse.setTimeOut(lockOptions.getTimeOut());
            lockOptionsToUse.setScope(lockOptions.getScope());
            afterLoadActions.add(new AfterLoadAction() {

                @Override
                public void afterLoad(SharedSessionContractImplementor session, Object entity, Loadable persister) {
                    ((Session) session).buildLockRequest(lockOptionsToUse).lock(persister.getEntityName(), entity);
                }
            });
            parameters.setLockOptions(new LockOptions());
            return sql;
        }
    }
    final LockOptions locks = new LockOptions(lockOptions.getLockMode());
    locks.setScope(lockOptions.getScope());
    locks.setTimeOut(lockOptions.getTimeOut());
    final Map<String, String[]> keyColumnNames = dialect.forUpdateOfColumns() ? new HashMap() : null;
    final String[] drivingSqlAliases = getAliases();
    for (int i = 0; i < drivingSqlAliases.length; i++) {
        final LockMode lockMode = lockOptions.getAliasSpecificLockMode(drivingSqlAliases[i]);
        if (lockMode != null) {
            final Lockable drivingPersister = (Lockable) getEntityPersisters()[i];
            final String rootSqlAlias = drivingPersister.getRootTableAlias(drivingSqlAliases[i]);
            locks.setAliasSpecificLockMode(rootSqlAlias, lockMode);
            if (keyColumnNames != null) {
                keyColumnNames.put(rootSqlAlias, drivingPersister.getRootTableIdentifierColumnNames());
            }
        }
    }
    return dialect.applyLocksToSql(sql, locks, keyColumnNames);
}
Also used : OuterJoinLoadable(org.hibernate.persister.entity.OuterJoinLoadable) Loadable(org.hibernate.persister.entity.Loadable) LockOptions(org.hibernate.LockOptions) HashMap(java.util.HashMap) AfterLoadAction(org.hibernate.loader.spi.AfterLoadAction) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) LockMode(org.hibernate.LockMode) Lockable(org.hibernate.persister.entity.Lockable) Session(org.hibernate.Session)

Example 40 with SharedSessionContractImplementor

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

the class EntityInsertAction method cacheAfterInsert.

private boolean cacheAfterInsert(EntityRegionAccessStrategy cache, Object ck) {
    SharedSessionContractImplementor session = getSession();
    final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
    try {
        eventListenerManager.cachePutStart();
        return cache.afterInsert(session, ck, cacheEntry, version);
    } finally {
        eventListenerManager.cachePutEnd();
    }
}
Also used : SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) SessionEventListenerManager(org.hibernate.engine.spi.SessionEventListenerManager)

Aggregations

SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)53 Test (org.junit.Test)16 CountDownLatch (java.util.concurrent.CountDownLatch)12 Session (org.hibernate.Session)10 EntityManager (javax.persistence.EntityManager)7 PutFromLoadValidator (org.hibernate.cache.infinispan.access.PutFromLoadValidator)7 EntityPersister (org.hibernate.persister.entity.EntityPersister)7 JtaTransactionCoordinatorImpl (org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl)7 Serializable (java.io.Serializable)6 AssertionFailedError (junit.framework.AssertionFailedError)6 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)6 HibernateException (org.hibernate.HibernateException)5 AssertionFailure (org.hibernate.AssertionFailure)4 TestForIssue (org.hibernate.testing.TestForIssue)4 SQLException (java.sql.SQLException)3 ArrayList (java.util.ArrayList)3 Arrays (java.util.Arrays)3 List (java.util.List)3 TimeUnit (java.util.concurrent.TimeUnit)3 Transaction (org.hibernate.Transaction)3