@@ -285,21 +285,28 @@ else if (!TransactionSynchronizationManager.isSynchronizationActive()) {
285
285
em = (!CollectionUtils .isEmpty (properties ) ? emf .createEntityManager (properties ) : emf .createEntityManager ());
286
286
}
287
287
288
- // Use same EntityManager for further JPA operations within the transaction.
289
- // Thread-bound object will get removed by synchronization at transaction completion.
290
- emHolder = new EntityManagerHolder (em );
291
- if (synchronizedWithTransaction ) {
292
- Object transactionData = prepareTransaction (em , emf );
293
- TransactionSynchronizationManager .registerSynchronization (
294
- new TransactionalEntityManagerSynchronization (emHolder , emf , transactionData , true ));
295
- emHolder .setSynchronizedWithTransaction (true );
288
+ try {
289
+ // Use same EntityManager for further JPA operations within the transaction.
290
+ // Thread-bound object will get removed by synchronization at transaction completion.
291
+ emHolder = new EntityManagerHolder (em );
292
+ if (synchronizedWithTransaction ) {
293
+ Object transactionData = prepareTransaction (em , emf );
294
+ TransactionSynchronizationManager .registerSynchronization (
295
+ new TransactionalEntityManagerSynchronization (emHolder , emf , transactionData , true ));
296
+ emHolder .setSynchronizedWithTransaction (true );
297
+ }
298
+ else {
299
+ // Unsynchronized - just scope it for the transaction, as demanded by the JPA 2.1 spec...
300
+ TransactionSynchronizationManager .registerSynchronization (
301
+ new TransactionScopedEntityManagerSynchronization (emHolder , emf ));
302
+ }
303
+ TransactionSynchronizationManager .bindResource (emf , emHolder );
296
304
}
297
- else {
298
- // Unsynchronized - just scope it for the transaction, as demanded by the JPA 2.1 spec.. .
299
- TransactionSynchronizationManager . registerSynchronization (
300
- new TransactionScopedEntityManagerSynchronization ( emHolder , emf )) ;
305
+ catch ( RuntimeException ex ) {
306
+ // Unexpected exception from external delegation call -> close EntityManager and rethrow .
307
+ closeEntityManager ( em );
308
+ throw ex ;
301
309
}
302
- TransactionSynchronizationManager .bindResource (emf , emHolder );
303
310
304
311
return em ;
305
312
}
0 commit comments