Skip to content

Commit 5cbb1fc

Browse files
committed
SpringSessionContext for Hibernate 4 supports lazily bound Session for propagation SUPPORTS
Issue: SPR-9020
1 parent 562916b commit 5cbb1fc

4 files changed

Lines changed: 102 additions & 18 deletions

File tree

‎spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/SessionFactoryUtils.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2013 the original author or authors.
2+
* Copyright 2002-2014 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -102,7 +102,9 @@ public abstract class SessionFactoryUtils {
102102
public static DataSource getDataSource(SessionFactory sessionFactory) {
103103
if (getConnectionProviderMethod != null && sessionFactory instanceof SessionFactoryImplementor) {
104104
Wrapped cp = (Wrapped) ReflectionUtils.invokeMethod(getConnectionProviderMethod, sessionFactory);
105-
return cp.unwrap(DataSource.class);
105+
if (cp != null) {
106+
return cp.unwrap(DataSource.class);
107+
}
106108
}
107109
return null;
108110
}

‎spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/SpringSessionContext.java‎

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2013 the original author or authors.
2+
* Copyright 2002-2014 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -17,7 +17,11 @@
1717
package org.springframework.orm.hibernate4;
1818

1919
import java.lang.reflect.Method;
20+
import javax.transaction.Status;
21+
import javax.transaction.SystemException;
22+
import javax.transaction.TransactionManager;
2023

24+
import org.apache.commons.logging.LogFactory;
2125
import org.hibernate.FlushMode;
2226
import org.hibernate.HibernateException;
2327
import org.hibernate.Session;
@@ -44,6 +48,8 @@ public class SpringSessionContext implements CurrentSessionContext {
4448

4549
private final SessionFactoryImplementor sessionFactory;
4650

51+
private TransactionManager transactionManager;
52+
4753
private CurrentSessionContext jtaSessionContext;
4854

4955

@@ -56,13 +62,14 @@ public SpringSessionContext(SessionFactoryImplementor sessionFactory) {
5662
try {
5763
Object jtaPlatform = sessionFactory.getServiceRegistry().getService(ConfigurableJtaPlatform.jtaPlatformClass);
5864
Method rtmMethod = ConfigurableJtaPlatform.jtaPlatformClass.getMethod("retrieveTransactionManager");
59-
Object transactionManager = ReflectionUtils.invokeMethod(rtmMethod, jtaPlatform);
60-
if (transactionManager != null) {
65+
this.transactionManager = (TransactionManager) ReflectionUtils.invokeMethod(rtmMethod, jtaPlatform);
66+
if (this.transactionManager != null) {
6167
this.jtaSessionContext = new SpringJtaSessionContext(sessionFactory);
6268
}
6369
}
6470
catch (Exception ex) {
65-
throw new IllegalStateException("Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex);
71+
LogFactory.getLog(SpringSessionContext.class).warn(
72+
"Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex);
6673
}
6774
}
6875

@@ -82,7 +89,7 @@ else if (value instanceof SessionHolder) {
8289
if (TransactionSynchronizationManager.isSynchronizationActive() &&
8390
!sessionHolder.isSynchronizedWithTransaction()) {
8491
TransactionSynchronizationManager.registerSynchronization(
85-
new SpringSessionSynchronization(sessionHolder, this.sessionFactory));
92+
new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
8693
sessionHolder.setSynchronizedWithTransaction(true);
8794
// Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
8895
// with FlushMode.MANUAL, which needs to allow flushing within the transaction.
@@ -95,15 +102,36 @@ else if (value instanceof SessionHolder) {
95102
}
96103
return session;
97104
}
98-
else if (this.jtaSessionContext != null) {
99-
Session session = this.jtaSessionContext.currentSession();
100-
if (TransactionSynchronizationManager.isSynchronizationActive()) {
101-
TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session));
105+
106+
if (this.transactionManager != null) {
107+
try {
108+
if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
109+
Session session = this.jtaSessionContext.currentSession();
110+
if (TransactionSynchronizationManager.isSynchronizationActive()) {
111+
TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session));
112+
}
113+
return session;
114+
}
115+
}
116+
catch (SystemException ex) {
117+
throw new HibernateException("JTA TransactionManager found but status check failed", ex);
118+
}
119+
}
120+
121+
if (TransactionSynchronizationManager.isSynchronizationActive()) {
122+
Session session = this.sessionFactory.openSession();
123+
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
124+
session.setFlushMode(FlushMode.MANUAL);
102125
}
126+
SessionHolder sessionHolder = new SessionHolder(session);
127+
TransactionSynchronizationManager.registerSynchronization(
128+
new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
129+
TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
130+
sessionHolder.setSynchronizedWithTransaction(true);
103131
return session;
104132
}
105133
else {
106-
throw new HibernateException("No Session found for current thread");
134+
throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
107135
}
108136
}
109137

‎spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/SpringSessionSynchronization.java‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2013 the original author or authors.
2+
* Copyright 2002-2014 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -39,12 +39,15 @@ class SpringSessionSynchronization implements TransactionSynchronization, Ordere
3939

4040
private final SessionFactory sessionFactory;
4141

42+
private final boolean newSession;
43+
4244
private boolean holderActive = true;
4345

4446

45-
public SpringSessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory) {
47+
public SpringSessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory, boolean newSession) {
4648
this.sessionHolder = sessionHolder;
4749
this.sessionFactory = sessionFactory;
50+
this.newSession = newSession;
4851
}
4952

5053
private Session getCurrentSession() {
@@ -111,6 +114,12 @@ public void beforeCompletion() {
111114
}
112115
// Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
113116
session.disconnect();
117+
118+
// Unbind at this point if it's a new Session...
119+
if (this.newSession) {
120+
TransactionSynchronizationManager.unbindResource(this.sessionFactory);
121+
this.holderActive = false;
122+
}
114123
}
115124

116125
@Override
@@ -128,6 +137,10 @@ public void afterCompletion(int status) {
128137
}
129138
finally {
130139
this.sessionHolder.setSynchronizedWithTransaction(false);
140+
// Call close() at this point if it's a new Session...
141+
if (this.newSession) {
142+
SessionFactoryUtils.closeSession(this.sessionHolder.getSession());
143+
}
131144
}
132145
}
133146

‎spring-orm-hibernate4/src/test/java/org/springframework/orm/hibernate4/HibernateTransactionManagerTests.java‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import java.util.ArrayList;
2424
import java.util.List;
2525
import java.util.Properties;
26-
2726
import javax.sql.DataSource;
2827
import javax.transaction.TransactionManager;
2928
import javax.transaction.TransactionSynchronizationRegistry;
@@ -38,13 +37,12 @@
3837
import org.hibernate.Transaction;
3938
import org.hibernate.cfg.AvailableSettings;
4039
import org.hibernate.dialect.HSQLDialect;
40+
import org.hibernate.engine.spi.SessionFactoryImplementor;
4141
import org.hibernate.engine.spi.SessionImplementor;
4242
import org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory;
4343
import org.hibernate.exception.ConstraintViolationException;
44-
4544
import org.junit.After;
4645
import org.junit.Test;
47-
4846
import org.mockito.InOrder;
4947

5048
import org.springframework.beans.factory.BeanFactory;
@@ -495,6 +493,49 @@ public Object doInTransaction(TransactionStatus status) {
495493
ordered.verify(session).close();
496494
}
497495

496+
@Test
497+
public void testTransactionWithPropagationSupportsAndCurrentSession() throws Exception {
498+
final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
499+
final Session session = mock(Session.class);
500+
501+
given(sf.openSession()).willReturn(session);
502+
given(session.getSessionFactory()).willReturn(sf);
503+
given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
504+
505+
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
506+
@Override
507+
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
508+
return sf;
509+
}
510+
};
511+
lsfb.afterPropertiesSet();
512+
final SessionFactory sfProxy = lsfb.getObject();
513+
514+
PlatformTransactionManager tm = new HibernateTransactionManager(sfProxy);
515+
TransactionTemplate tt = new TransactionTemplate(tm);
516+
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
517+
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
518+
519+
tt.execute(new TransactionCallback() {
520+
@Override
521+
public Object doInTransaction(TransactionStatus status) {
522+
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
523+
assertTrue("Is not new transaction", !status.isNewTransaction());
524+
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
525+
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
526+
Session session = new SpringSessionContext(sf).currentSession();
527+
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sfProxy));
528+
session.flush();
529+
return null;
530+
}
531+
});
532+
533+
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
534+
InOrder ordered = inOrder(session);
535+
ordered.verify(session).flush();
536+
ordered.verify(session).close();
537+
}
538+
498539
@Test
499540
public void testTransactionWithPropagationSupportsAndInnerTransaction() throws Exception {
500541
final SessionFactory sf = mock(SessionFactory.class);
@@ -735,7 +776,7 @@ public Object doInTransaction(TransactionStatus status) {
735776
catch (DataIntegrityViolationException ex) {
736777
// expected
737778
assertEquals(rootCause, ex.getCause());
738-
assertTrue(ex.getMessage().indexOf("mymsg") != -1);
779+
assertTrue(ex.getMessage().contains("mymsg"));
739780
}
740781

741782
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

0 commit comments

Comments
 (0)