|
39 | 39 | import org.springframework.transaction.TransactionDefinition;
|
40 | 40 | import org.springframework.transaction.TransactionException;
|
41 | 41 | import org.springframework.transaction.support.TransactionSynchronizationManager;
|
| 42 | +import org.springframework.util.ClassUtils; |
42 | 43 | import org.springframework.util.ReflectionUtils;
|
43 | 44 |
|
44 | 45 | /**
|
|
53 | 54 | */
|
54 | 55 | public class HibernateJpaDialect extends DefaultJpaDialect {
|
55 | 56 |
|
| 57 | + private static final Method getEntityManagerFactoryMethod = |
| 58 | + ClassUtils.getMethodIfAvailable(EntityManager.class, "getEntityManagerFactory"); |
| 59 | + |
| 60 | + |
56 | 61 | @Override
|
57 | 62 | public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
|
58 | 63 | throws PersistenceException, SQLException, TransactionException {
|
@@ -83,10 +88,15 @@ public Object prepareTransaction(EntityManager entityManager, boolean readOnly,
|
83 | 88 | previousFlushMode = flushMode;
|
84 | 89 | }
|
85 | 90 | }
|
86 |
| - EntityManagerFactory emf = entityManager.getEntityManagerFactory(); |
87 |
| - if (emf instanceof HibernateEntityManagerFactory) { |
88 |
| - SessionFactory sf = ((HibernateEntityManagerFactory) emf).getSessionFactory(); |
89 |
| - TransactionSynchronizationManager.bindResource(sf, session); |
| 91 | + if (getEntityManagerFactoryMethod != null) { |
| 92 | + // We're on JPA 2.0, enabling our exposure of the underlying Session |
| 93 | + // to the underlying SessionFactory as transaction resource reference. |
| 94 | + EntityManagerFactory emf = |
| 95 | + (EntityManagerFactory) ReflectionUtils.invokeMethod(getEntityManagerFactoryMethod, entityManager); |
| 96 | + if (emf instanceof HibernateEntityManagerFactory) { |
| 97 | + SessionFactory sf = ((HibernateEntityManagerFactory) emf).getSessionFactory(); |
| 98 | + TransactionSynchronizationManager.bindResource(sf, session); |
| 99 | + } |
90 | 100 | }
|
91 | 101 | return new SessionTransactionData(session, previousFlushMode);
|
92 | 102 | }
|
|
0 commit comments