hibernate/hibernate-orm · error · DetachedObjectException

Given proxy does not belong to this persistence context

Error message

Given proxy does not belong to this persistence context

What it means

The given proxy's LazyInitializer is bound to a different session (or none) than the one supplied, so it cannot be initialized through that persistence context — a detached-proxy misuse. Reattach the proxy to the session or fetch the entity within the current session.

Solutions

  1. Only operate on proxies loaded by the current session/persistence context
  2. Reload the entity in the current session instead of passing a proxy from another session
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at hibernate-core/src/main/java/org/hibernate/engine/internal/ProxyUtil.java:54 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of hibernate/hibernate-orm@fad1729dce (2026-08-22). Data as JSON: /api/errors/646644d7acdadeb1. Report an issue: GitHub.

Appendix: source

Thrown at hibernate-core/src/main/java/org/hibernate/engine/internal/ProxyUtil.java:54

			return lazyInitializer.getImplementation();
		}
		else {
			return maybeProxy;
		}
	}

	/**
	 * Get the entity instance underlying the given proxy, forcing
	 * initialization if the proxy is uninitialized. If the given
	 * object is not a proxy, simply return the argument.
	 * @throws DetachedObjectException if the given proxy does not
	 *         belong to the given session
	 */
	public static Object forceInitialize(Object maybeProxy, SharedSessionContractImplementor session) {
		final var lazyInitializer = extractLazyInitializer( maybeProxy );
		if ( lazyInitializer != null ) {
			if ( lazyInitializer.getSession() != session ) {
				throw new DetachedObjectException( "Given proxy does not belong to this persistence context" );
			}
			//initialize + unwrap the object and return it
			return lazyInitializer.getImplementation();
		}
		else if ( isPersistentAttributeInterceptable( maybeProxy ) ) {
			final var interceptor =
					asPersistentAttributeInterceptable( maybeProxy )
							.$$_hibernate_getInterceptor();
			if ( interceptor instanceof EnhancementAsProxyLazinessInterceptor lazinessInterceptor ) {
				if ( lazinessInterceptor.getLinkedSession() != session ) {
					throw new DetachedObjectException( "Given proxy does not belong to this persistence context" );
				}
				lazinessInterceptor.forceInitialize( maybeProxy, null );
			}
			return maybeProxy;
		}
		else {
			return maybeProxy;

View on GitHub (pinned to fad1729dce)