From b4dcb36b213695089d13738b759c74744b33d1dc Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 13 Oct 2025 14:17:07 +0200 Subject: [PATCH] Align currentStatelessSession() implementation with currentSession() See gh-7184 --- .../jpa/hibernate/SpringSessionContext.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/hibernate/SpringSessionContext.java b/spring-orm/src/main/java/org/springframework/orm/jpa/hibernate/SpringSessionContext.java index 10e238a897a..3d6c81a5dfa 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/hibernate/SpringSessionContext.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/hibernate/SpringSessionContext.java @@ -171,9 +171,6 @@ public class SpringSessionContext implements CurrentSessionContext { * @return the current StatelessSession */ public static StatelessSession currentStatelessSession(SessionFactory sessionFactory) { - if (!TransactionSynchronizationManager.isSynchronizationActive()) { - throw new HibernateException("Could not obtain transaction-synchronized Session for current thread"); - } Object value = TransactionSynchronizationManager.getResource(sessionFactory); if (value instanceof StatelessSession statelessSession) { return statelessSession; @@ -185,14 +182,20 @@ public class SpringSessionContext implements CurrentSessionContext { } holder = sessionHolder; } - StatelessSession session = sessionFactory.openStatelessSession(determineConnection(sessionFactory, holder)); - if (holder != null) { - holder.setStatelessSession(session); + + if (TransactionSynchronizationManager.isSynchronizationActive()) { + StatelessSession session = sessionFactory.openStatelessSession(determineConnection(sessionFactory, holder)); + if (holder != null) { + holder.setStatelessSession(session); + } + else { + bindSessionHolder(sessionFactory, new SessionHolder(session)); + } + return session; } else { - bindSessionHolder(sessionFactory, new SessionHolder(session)); + throw new HibernateException("Could not obtain transaction-synchronized Session for current thread"); } - return session; } private static void bindSessionHolder(SessionFactory sessionFactory, SessionHolder holder) {