jamesfredley commented on code in PR #16763:
URL: https://github.com/apache/grails-core/pull/16763#discussion_r4373361074


##########
grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/GrailsHibernateTemplate.java:
##########
@@ -236,6 +239,30 @@ public <T> T executeWithNewSession(final Closure<T> 
callable) {
                 txResources.initSynchronization();
             }
 
+            // If the outer session is disconnected, acquire its physical 
connection now before
+            // unbinding and entering the new session scope. Otherwise, lazy 
loading on outer session
+            // entities inside withNewSession { withTransaction { ... } } 
would borrow the inner
+            // transaction's connection and be left with a closed connection 
when the inner transaction commits.
+            if (previousHolder != null && previousHolder.getSession() != null 
&& previousHolder.getSession().isOpen()) {
+                Session previousSession = previousHolder.getSession();
+                if (previousSession instanceof SessionImplementor sessionImpl) 
{
+                    JdbcCoordinator jdbcCoordinator = 
sessionImpl.getJdbcCoordinator();
+                    if (jdbcCoordinator != null) {
+                        LogicalConnectionImplementor logicalConnection = 
jdbcCoordinator.getLogicalConnection();
+                        if (logicalConnection != null && 
!logicalConnection.isPhysicallyConnected()) {
+                            Connection con = 
logicalConnection.getPhysicalConnection();

Review Comment:
   This acquires the outer connection after `previousConnectionHolder` was 
saved as null, and after synchronization was suspended. 
`TransactionAwareDataSourceProxy` binds a new holder. The cleanup does not 
unbind it, because it still thinks there was none. A nested `withTransaction` 
can then fail with "Already value bound", and cleanup can release the outer 
connection.
   
   Acquire that connection before saving the holder and the synchronization 
list. Please cover a `SUPPORTS` scope with a disconnected request session and 
no bound DataSource holder.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to