|
16 | 16 |
|
17 | 17 | package org.springframework.orm.jpa; |
18 | 18 |
|
| 19 | +import java.lang.reflect.Method; |
19 | 20 | import java.util.Map; |
20 | 21 | import javax.persistence.EntityExistsException; |
21 | 22 | import javax.persistence.EntityManager; |
|
45 | 46 | import org.springframework.transaction.support.ResourceHolderSynchronization; |
46 | 47 | import org.springframework.transaction.support.TransactionSynchronizationManager; |
47 | 48 | import org.springframework.util.Assert; |
| 49 | +import org.springframework.util.ClassUtils; |
48 | 50 | import org.springframework.util.CollectionUtils; |
| 51 | +import org.springframework.util.ReflectionUtils; |
49 | 52 | import org.springframework.util.StringUtils; |
50 | 53 |
|
51 | 54 | /** |
@@ -71,6 +74,25 @@ public abstract class EntityManagerFactoryUtils { |
71 | 74 |
|
72 | 75 | private static final Log logger = LogFactory.getLog(EntityManagerFactoryUtils.class); |
73 | 76 |
|
| 77 | + private static Method createEntityManagerWithSynchronizationTypeMethod; |
| 78 | + |
| 79 | + private static Object synchronizationTypeUnsynchronized; |
| 80 | + |
| 81 | + static { |
| 82 | + try { |
| 83 | + @SuppressWarnings("unchecked") |
| 84 | + Class<Enum> synchronizationTypeClass = (Class<Enum>) ClassUtils.forName( |
| 85 | + "javax.persistence.SynchronizationType", EntityManagerFactoryUtils.class.getClassLoader()); |
| 86 | + createEntityManagerWithSynchronizationTypeMethod = EntityManagerFactory.class.getMethod( |
| 87 | + "createEntityManager", synchronizationTypeClass, Map.class); |
| 88 | + synchronizationTypeUnsynchronized = Enum.valueOf(synchronizationTypeClass, "UNSYNCHRONIZED"); |
| 89 | + } |
| 90 | + catch (Exception ex) { |
| 91 | + // No JPA 2.1 API available |
| 92 | + createEntityManagerWithSynchronizationTypeMethod = null; |
| 93 | + } |
| 94 | + } |
| 95 | + |
74 | 96 |
|
75 | 97 | /** |
76 | 98 | * Find an EntityManagerFactory with the given name in the given |
@@ -146,7 +168,7 @@ public static EntityManager getTransactionalEntityManager(EntityManagerFactory e |
146 | 168 | public static EntityManager getTransactionalEntityManager(EntityManagerFactory emf, Map properties) |
147 | 169 | throws DataAccessResourceFailureException { |
148 | 170 | try { |
149 | | - return doGetTransactionalEntityManager(emf, properties); |
| 171 | + return doGetTransactionalEntityManager(emf, properties, true); |
150 | 172 | } |
151 | 173 | catch (PersistenceException ex) { |
152 | 174 | throw new DataAccessResourceFailureException("Could not obtain JPA EntityManager", ex); |
@@ -166,53 +188,113 @@ public static EntityManager getTransactionalEntityManager(EntityManagerFactory e |
166 | 188 | * @see #getTransactionalEntityManager(javax.persistence.EntityManagerFactory) |
167 | 189 | * @see JpaTransactionManager |
168 | 190 | */ |
| 191 | + public static EntityManager doGetTransactionalEntityManager(EntityManagerFactory emf, Map properties) |
| 192 | + throws PersistenceException { |
| 193 | + |
| 194 | + return doGetTransactionalEntityManager(emf, properties, true); |
| 195 | + } |
| 196 | + |
| 197 | + /** |
| 198 | + * Obtain a JPA EntityManager from the given factory. Is aware of a |
| 199 | + * corresponding EntityManager bound to the current thread, |
| 200 | + * for example when using JpaTransactionManager. |
| 201 | + * <p>Same as {@code getEntityManager}, but throwing the original PersistenceException. |
| 202 | + * @param emf EntityManagerFactory to create the EntityManager with |
| 203 | + * @param properties the properties to be passed into the {@code createEntityManager} |
| 204 | + * call (may be {@code null}) |
| 205 | + * @param synchronizedWithTransaction whether to automatically join ongoing |
| 206 | + * transactions (according to the JPA 2.1 SynchronizationType rules) |
| 207 | + * @return the EntityManager, or {@code null} if none found |
| 208 | + * @throws javax.persistence.PersistenceException if the EntityManager couldn't be created |
| 209 | + * @see #getTransactionalEntityManager(javax.persistence.EntityManagerFactory) |
| 210 | + * @see JpaTransactionManager |
| 211 | + */ |
169 | 212 | public static EntityManager doGetTransactionalEntityManager( |
170 | | - EntityManagerFactory emf, Map properties) throws PersistenceException { |
| 213 | + EntityManagerFactory emf, Map properties, boolean synchronizedWithTransaction) throws PersistenceException { |
171 | 214 |
|
172 | 215 | Assert.notNull(emf, "No EntityManagerFactory specified"); |
173 | 216 |
|
174 | 217 | EntityManagerHolder emHolder = |
175 | 218 | (EntityManagerHolder) TransactionSynchronizationManager.getResource(emf); |
176 | 219 | if (emHolder != null) { |
177 | | - if (!emHolder.isSynchronizedWithTransaction() && |
178 | | - TransactionSynchronizationManager.isSynchronizationActive()) { |
179 | | - // Try to explicitly synchronize the EntityManager itself |
180 | | - // with an ongoing JTA transaction, if any. |
181 | | - try { |
182 | | - emHolder.getEntityManager().joinTransaction(); |
| 220 | + if (synchronizedWithTransaction) { |
| 221 | + if (!emHolder.isSynchronizedWithTransaction() && |
| 222 | + TransactionSynchronizationManager.isSynchronizationActive()) { |
| 223 | + // Try to explicitly synchronize the EntityManager itself |
| 224 | + // with an ongoing JTA transaction, if any. |
| 225 | + try { |
| 226 | + emHolder.getEntityManager().joinTransaction(); |
| 227 | + } |
| 228 | + catch (TransactionRequiredException ex) { |
| 229 | + logger.debug("Could not join transaction because none was actually active", ex); |
| 230 | + } |
| 231 | + Object transactionData = prepareTransaction(emHolder.getEntityManager(), emf); |
| 232 | + TransactionSynchronizationManager.registerSynchronization( |
| 233 | + new TransactionalEntityManagerSynchronization(emHolder, emf, transactionData, false)); |
| 234 | + emHolder.setSynchronizedWithTransaction(true); |
183 | 235 | } |
184 | | - catch (TransactionRequiredException ex) { |
185 | | - logger.debug("Could not join JTA transaction because none was active", ex); |
| 236 | + // Use holder's reference count to track synchronizedWithTransaction access. |
| 237 | + // isOpen() check used below to find out about it. |
| 238 | + emHolder.requested(); |
| 239 | + return emHolder.getEntityManager(); |
| 240 | + } |
| 241 | + else { |
| 242 | + // unsynchronized EntityManager demanded |
| 243 | + if (emHolder.isTransactionActive() && !emHolder.isOpen()) { |
| 244 | + if (!TransactionSynchronizationManager.isSynchronizationActive()) { |
| 245 | + return null; |
| 246 | + } |
| 247 | + // EntityManagerHolder with an active transaction coming from JpaTransactionManager, |
| 248 | + // with no synchronized EntityManager having been requested by application code before. |
| 249 | + // Unbind in order to register a new unsynchronized EntityManager instead. |
| 250 | + TransactionSynchronizationManager.unbindResource(emf); |
| 251 | + } |
| 252 | + else { |
| 253 | + // Either a previously bound unsynchronized EntityManager, or the application |
| 254 | + // has requested a synchronized EntityManager before and therefore upgraded |
| 255 | + // this transaction's EntityManager to synchronized before. |
| 256 | + return emHolder.getEntityManager(); |
186 | 257 | } |
187 | | - Object transactionData = prepareTransaction(emHolder.getEntityManager(), emf); |
188 | | - TransactionSynchronizationManager.registerSynchronization( |
189 | | - new EntityManagerSynchronization(emHolder, emf, transactionData, false)); |
190 | | - emHolder.setSynchronizedWithTransaction(true); |
191 | 258 | } |
192 | | - return emHolder.getEntityManager(); |
193 | 259 | } |
194 | | - |
195 | | - if (!TransactionSynchronizationManager.isSynchronizationActive()) { |
| 260 | + else if (!TransactionSynchronizationManager.isSynchronizationActive()) { |
196 | 261 | // Indicate that we can't obtain a transactional EntityManager. |
197 | 262 | return null; |
198 | 263 | } |
199 | 264 |
|
200 | 265 | // Create a new EntityManager for use within the current transaction. |
201 | 266 | logger.debug("Opening JPA EntityManager"); |
202 | | - EntityManager em = |
203 | | - (!CollectionUtils.isEmpty(properties) ? emf.createEntityManager(properties) : emf.createEntityManager()); |
204 | | - |
205 | | - if (TransactionSynchronizationManager.isSynchronizationActive()) { |
206 | | - logger.debug("Registering transaction synchronization for JPA EntityManager"); |
207 | | - // Use same EntityManager for further JPA actions within the transaction. |
208 | | - // Thread object will get removed by synchronization at transaction completion. |
209 | | - emHolder = new EntityManagerHolder(em); |
| 267 | + EntityManager em = null; |
| 268 | + if (!synchronizedWithTransaction && createEntityManagerWithSynchronizationTypeMethod != null) { |
| 269 | + try { |
| 270 | + em = (EntityManager) ReflectionUtils.invokeMethod(createEntityManagerWithSynchronizationTypeMethod, |
| 271 | + emf, synchronizationTypeUnsynchronized, properties); |
| 272 | + } |
| 273 | + catch (AbstractMethodError err) { |
| 274 | + // JPA 2.1 API available but method not actually implemented in persistence provider: |
| 275 | + // falling back to regular createEntityManager method. |
| 276 | + } |
| 277 | + } |
| 278 | + if (em == null) { |
| 279 | + em = (!CollectionUtils.isEmpty(properties) ? emf.createEntityManager(properties) : emf.createEntityManager()); |
| 280 | + } |
| 281 | + |
| 282 | + // Use same EntityManager for further JPA actions within the transaction. |
| 283 | + // Thread object will get removed by synchronization at transaction completion. |
| 284 | + logger.debug("Registering transaction synchronization for JPA EntityManager"); |
| 285 | + emHolder = new EntityManagerHolder(em); |
| 286 | + if (synchronizedWithTransaction) { |
210 | 287 | Object transactionData = prepareTransaction(em, emf); |
211 | 288 | TransactionSynchronizationManager.registerSynchronization( |
212 | | - new EntityManagerSynchronization(emHolder, emf, transactionData, true)); |
| 289 | + new TransactionalEntityManagerSynchronization(emHolder, emf, transactionData, true)); |
213 | 290 | emHolder.setSynchronizedWithTransaction(true); |
214 | | - TransactionSynchronizationManager.bindResource(emf, emHolder); |
215 | 291 | } |
| 292 | + else { |
| 293 | + // unsynchronized - just scope it for the transaction, as demanded by the JPA 2.1 spec |
| 294 | + TransactionSynchronizationManager.registerSynchronization( |
| 295 | + new TransactionScopedEntityManagerSynchronization(emHolder, emf)); |
| 296 | + } |
| 297 | + TransactionSynchronizationManager.bindResource(emf, emHolder); |
216 | 298 |
|
217 | 299 | return em; |
218 | 300 | } |
@@ -356,7 +438,7 @@ public static void closeEntityManager(EntityManager em) { |
356 | 438 | * (e.g. when participating in a JtaTransactionManager transaction). |
357 | 439 | * @see org.springframework.transaction.jta.JtaTransactionManager |
358 | 440 | */ |
359 | | - private static class EntityManagerSynchronization |
| 441 | + private static class TransactionalEntityManagerSynchronization |
360 | 442 | extends ResourceHolderSynchronization<EntityManagerHolder, EntityManagerFactory> |
361 | 443 | implements Ordered { |
362 | 444 |
|
@@ -366,7 +448,7 @@ private static class EntityManagerSynchronization |
366 | 448 |
|
367 | 449 | private final boolean newEntityManager; |
368 | 450 |
|
369 | | - public EntityManagerSynchronization( |
| 451 | + public TransactionalEntityManagerSynchronization( |
370 | 452 | EntityManagerHolder emHolder, EntityManagerFactory emf, Object txData, boolean newEm) { |
371 | 453 | super(emHolder, emf); |
372 | 454 | this.transactionData = txData; |
@@ -381,8 +463,17 @@ public int getOrder() { |
381 | 463 |
|
382 | 464 | @Override |
383 | 465 | protected void flushResource(EntityManagerHolder resourceHolder) { |
| 466 | + EntityManager em = resourceHolder.getEntityManager(); |
| 467 | + if (em instanceof EntityManagerProxy) { |
| 468 | + EntityManager target = ((EntityManagerProxy) em).getTargetEntityManager(); |
| 469 | + if (TransactionSynchronizationManager.hasResource(target)) { |
| 470 | + // ExtendedEntityManagerSynchronization active after joinTransaction() call: |
| 471 | + // flush synchronization already registered. |
| 472 | + return; |
| 473 | + } |
| 474 | + } |
384 | 475 | try { |
385 | | - resourceHolder.getEntityManager().flush(); |
| 476 | + em.flush(); |
386 | 477 | } |
387 | 478 | catch (RuntimeException ex) { |
388 | 479 | if (this.jpaDialect != null) { |
@@ -415,4 +506,26 @@ protected void cleanupResource(EntityManagerHolder resourceHolder, EntityManager |
415 | 506 | } |
416 | 507 | } |
417 | 508 |
|
| 509 | + |
| 510 | + /** |
| 511 | + * Minimal callback that just closes the EntityManager at the end of the transaction. |
| 512 | + */ |
| 513 | + private static class TransactionScopedEntityManagerSynchronization |
| 514 | + extends ResourceHolderSynchronization<EntityManagerHolder, EntityManagerFactory> |
| 515 | + implements Ordered { |
| 516 | + |
| 517 | + public TransactionScopedEntityManagerSynchronization(EntityManagerHolder emHolder, EntityManagerFactory emf) { |
| 518 | + super(emHolder, emf); |
| 519 | + } |
| 520 | + |
| 521 | + public int getOrder() { |
| 522 | + return ENTITY_MANAGER_SYNCHRONIZATION_ORDER + 1; |
| 523 | + } |
| 524 | + |
| 525 | + @Override |
| 526 | + protected void releaseResource(EntityManagerHolder resourceHolder, EntityManagerFactory resourceKey) { |
| 527 | + closeEntityManager(resourceHolder.getEntityManager()); |
| 528 | + } |
| 529 | + } |
| 530 | + |
418 | 531 | } |