@@ -266,21 +266,28 @@ else if (!TransactionSynchronizationManager.isSynchronizationActive()) {
266
266
em = (!CollectionUtils .isEmpty (properties ) ? emf .createEntityManager (properties ) : emf .createEntityManager ());
267
267
}
268
268
269
- // Use same EntityManager for further JPA operations within the transaction.
270
- // Thread-bound object will get removed by synchronization at transaction completion.
271
- emHolder = new EntityManagerHolder (em );
272
- if (synchronizedWithTransaction ) {
273
- Object transactionData = prepareTransaction (em , emf );
274
- TransactionSynchronizationManager .registerSynchronization (
275
- new TransactionalEntityManagerSynchronization (emHolder , emf , transactionData , true ));
276
- emHolder .setSynchronizedWithTransaction (true );
269
+ try {
270
+ // Use same EntityManager for further JPA operations within the transaction.
271
+ // Thread-bound object will get removed by synchronization at transaction completion.
272
+ emHolder = new EntityManagerHolder (em );
273
+ if (synchronizedWithTransaction ) {
274
+ Object transactionData = prepareTransaction (em , emf );
275
+ TransactionSynchronizationManager .registerSynchronization (
276
+ new TransactionalEntityManagerSynchronization (emHolder , emf , transactionData , true ));
277
+ emHolder .setSynchronizedWithTransaction (true );
278
+ }
279
+ else {
280
+ // Unsynchronized - just scope it for the transaction, as demanded by the JPA 2.1 spec...
281
+ TransactionSynchronizationManager .registerSynchronization (
282
+ new TransactionScopedEntityManagerSynchronization (emHolder , emf ));
283
+ }
284
+ TransactionSynchronizationManager .bindResource (emf , emHolder );
277
285
}
278
- else {
279
- // Unsynchronized - just scope it for the transaction, as demanded by the JPA 2.1 spec.. .
280
- TransactionSynchronizationManager . registerSynchronization (
281
- new TransactionScopedEntityManagerSynchronization ( emHolder , emf )) ;
286
+ catch ( RuntimeException ex ) {
287
+ // Unexpected exception from external delegation call -> close EntityManager and rethrow .
288
+ closeEntityManager ( em );
289
+ throw ex ;
282
290
}
283
- TransactionSynchronizationManager .bindResource (emf , emHolder );
284
291
285
292
return em ;
286
293
}
0 commit comments