Java Code Examples for org.hibernate.engine.spi.SessionImplementor#getPersistenceContextInternal()

The following examples show how to use org.hibernate.engine.spi.SessionImplementor#getPersistenceContextInternal() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 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 CompletionStage<Boolean> isTransient(String entityName, Object entity, Boolean assumed,
												   SessionImplementor session) {
	if ( entity == LazyPropertyInitializer.UNFETCHED_PROPERTY ) {
		// an unfetched association can only point to
		// an entity that already exists in the db
		return CompletionStages.falseFuture();
	}

	// let the interceptor inspect the instance to decide
	Boolean isUnsaved = session.getInterceptor().isTransient( entity );
	if ( isUnsaved != null ) {
		return CompletionStages.completedFuture( 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 CompletionStages.completedFuture( isUnsaved );
	}

	// we use the assumed value, if there is one, to avoid hitting
	// the database
	if ( assumed != null ) {
		return CompletionStages.completedFuture( assumed );
	}

	// hit the database, after checking the session cache for a snapshot
	ReactivePersistenceContextAdapter persistenceContext =
			(ReactivePersistenceContextAdapter) session.getPersistenceContextInternal();
	Serializable id = persister.getIdentifier(entity, session);
	return persistenceContext.reactiveGetDatabaseSnapshot( id, persister).thenApply(Objects::isNull);
}
 
Example 2
/**
 * 1. Recreate the collection key to collection map
 * 2. rebuild the collection entries
 * 3. call Interceptor.postFlush()
 */
protected void postFlush(SessionImplementor session) throws HibernateException {

	LOG.trace( "Post flush" );

	final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
	persistenceContext.clearCollectionsByKey();

	// the database has changed now, so the subselect results need to be invalidated
	// the batch fetching queues should also be cleared - especially the collection batch fetching one
	persistenceContext.getBatchFetchQueue().clear();

	persistenceContext.forEachCollectionEntry(
			(persistentCollection, collectionEntry) -> {
				collectionEntry.postFlush( persistentCollection );
				if ( collectionEntry.getLoadedPersister() == null ) {
					//if the collection is dereferenced, unset its session reference and remove from the session cache
					//iter.remove(); //does not work, since the entrySet is not backed by the set
					persistentCollection.unsetSession( session );
					persistenceContext.removeCollectionEntry( persistentCollection );
				}
				else {
					//otherwise recreate the mapping between the collection and its key
					CollectionKey collectionKey = new CollectionKey(
							collectionEntry.getLoadedPersister(),
							collectionEntry.getLoadedKey()
					);
					persistenceContext.addCollectionByKey( collectionKey, persistentCollection );
				}
			}, true
	);
}
 
Example 3
@Override
public CompletionStage<Void> reactiveOnLock(LockEvent event) throws HibernateException {
	if ( event.getObject() == null ) {
		throw new NullPointerException( "attempted to lock null" );
	}

	if ( event.getLockMode() == LockMode.WRITE ) {
		throw new HibernateException( "Invalid lock mode for lock()" );
	}

	if ( event.getLockMode() == LockMode.UPGRADE_SKIPLOCKED ) {
		log.explicitSkipLockedLockCombo();
	}

	SessionImplementor source = event.getSession();
	final PersistenceContext persistenceContext = source.getPersistenceContextInternal();
	Object entity = persistenceContext.unproxyAndReassociate( event.getObject() );
	//TODO: if object was an uninitialized proxy, this is inefficient,
	//      resulting in two SQL selects

	EntityEntry entry = persistenceContext.getEntry(entity);
	CompletionStage<EntityEntry> stage;
	if (entry==null) {
		final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );
		final Serializable id = persister.getIdentifier( entity, source );
		stage = ForeignKeys.isNotTransient( event.getEntityName(), entity, Boolean.FALSE, source )
				.thenApply(
						trans -> {
							if (!trans) {
								throw new TransientObjectException(
										"cannot lock an unsaved transient instance: " +
												persister.getEntityName()
								);
							}

							EntityEntry e = reassociate(event, entity, id, persister);
							cascadeOnLock(event, persister, entity);
							return e;
						} );

	}
	else {
		stage = CompletionStages.completedFuture(entry);
	}

	return stage.thenCompose( e -> upgradeLock( entity, e, event.getLockOptions(), event.getSession() ) );
}
 
Example 4
/**
 * Try to initialize a collection from the cache
 *
 * @param id The id of the collection to initialize
 * @param persister The collection persister
 * @param collection The collection to initialize
 * @param source The originating session
 *
 * @return true if we were able to initialize the collection from the cache;
 *         false otherwise.
 */
private boolean initializeCollectionFromCache(
		Serializable id,
		CollectionPersister persister,
		PersistentCollection collection,
		SessionImplementor source) {

	if ( source.getLoadQueryInfluencers().hasEnabledFilters() && persister.isAffectedByEnabledFilters( source ) ) {
		LOG.trace( "Disregarding cached version (if any) of collection due to enabled filters" );
		return false;
	}

	final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled();

	if ( !useCache ) {
		return false;
	}

	final SessionFactoryImplementor factory = source.getFactory();
	final CollectionDataAccess cacheAccessStrategy = persister.getCacheAccessStrategy();
	final Object ck = cacheAccessStrategy.generateCacheKey( id, persister, factory, source.getTenantIdentifier() );
	final Object ce = CacheHelper.fromSharedCache( source, ck, cacheAccessStrategy );

	final StatisticsImplementor statistics = factory.getStatistics();
	if ( statistics.isStatisticsEnabled() ) {
		if ( ce == null ) {
			statistics.collectionCacheMiss( persister.getNavigableRole(), cacheAccessStrategy.getRegion().getName() );
		}
		else {
			statistics.collectionCacheHit( persister.getNavigableRole(), cacheAccessStrategy.getRegion().getName() );
		}
	}

	if ( ce == null ) {
		return false;
	}

	CollectionCacheEntry cacheEntry = (CollectionCacheEntry) persister.getCacheEntryStructure().destructure( ce, factory );

	final PersistenceContext persistenceContext = source.getPersistenceContextInternal();
	cacheEntry.assemble( collection, persister, persistenceContext.getCollectionOwner( id, persister ) );
	persistenceContext.getCollectionEntry( collection ).postInitialize( collection );
	return true;
}