GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — JPA 2.1 support, in particular for SynchronizationType.UNSYNCHRONIZED · candrews/spring-framework@ff160f9

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • spring-orm/src
    • main/java/org/springframework/orm/jpa
      • AbstractEntityManagerFactoryBean.java
      • EntityManagerFactoryUtils.java
      • ExtendedEntityManagerCreator.java
      • JpaDialect.java
      • JpaTransactionManager.java
      • SharedEntityManagerCreator.java
      • support
        • PersistenceAnnotationBeanPostProcessor.java
        • SharedEntityManagerBean.java
    • test/java/org/springframework/orm/jpa
      • AbstractContainerEntityManagerFactoryIntegrationTests.java
      • LocalContainerEntityManagerFactoryBeanTests.java
      • LocalEntityManagerFactoryBeanTests.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java‎

Copy file name to clipboardExpand all lines: spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java
+14-2Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2012 the original author or authors.
2+
* Copyright 2002-2013 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.
@@ -373,10 +373,22 @@ Object invokeProxyMethod(Method method, Object[] args) throws Throwable {
373373
else if (method.getDeclaringClass().equals(EntityManagerFactoryPlusOperations.class)) {
374374
return method.invoke(this.plusOperations, args);
375375
}
376+
else if (method.getName().equals("createEntityManager") && args != null && args.length > 0 &&
377+
args[0] != null && args[0].getClass().isEnum() && "SYNCHRONIZED".equals(args[0].toString())) {
378+
// JPA 2.1's createEntityManager(SynchronizationType, Map)
379+
// Redirect to plain createEntityManager and add synchronization semantics through Spring proxy
380+
EntityManager rawEntityManager = (args.length > 1 ?
381+
this.nativeEntityManagerFactory.createEntityManager((Map) args[1]) :
382+
this.nativeEntityManagerFactory.createEntityManager());
383+
return ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, true);
384+
}
385+
386+
// Standard delegation to the native factory, just post-processing EntityManager return values
376387
Object retVal = method.invoke(this.nativeEntityManagerFactory, args);
377388
if (retVal instanceof EntityManager) {
389+
// Any other createEntityManager variant - expecting non-synchronized semantics
378390
EntityManager rawEntityManager = (EntityManager) retVal;
379-
retVal = ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this);
391+
retVal = ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, false);
380392
}
381393
return retVal;
382394
}
Collapse file

‎spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java‎

Copy file name to clipboardExpand all lines: spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java
+143-30Lines changed: 143 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package org.springframework.orm.jpa;
1818

19+
import java.lang.reflect.Method;
1920
import java.util.Map;
2021
import javax.persistence.EntityExistsException;
2122
import javax.persistence.EntityManager;
@@ -45,7 +46,9 @@
4546
import org.springframework.transaction.support.ResourceHolderSynchronization;
4647
import org.springframework.transaction.support.TransactionSynchronizationManager;
4748
import org.springframework.util.Assert;
49+
import org.springframework.util.ClassUtils;
4850
import org.springframework.util.CollectionUtils;
51+
import org.springframework.util.ReflectionUtils;
4952
import org.springframework.util.StringUtils;
5053

5154
/**
@@ -71,6 +74,25 @@ public abstract class EntityManagerFactoryUtils {
7174

7275
private static final Log logger = LogFactory.getLog(EntityManagerFactoryUtils.class);
7376

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+
7496

7597
/**
7698
* Find an EntityManagerFactory with the given name in the given
@@ -146,7 +168,7 @@ public static EntityManager getTransactionalEntityManager(EntityManagerFactory e
146168
public static EntityManager getTransactionalEntityManager(EntityManagerFactory emf, Map properties)
147169
throws DataAccessResourceFailureException {
148170
try {
149-
return doGetTransactionalEntityManager(emf, properties);
171+
return doGetTransactionalEntityManager(emf, properties, true);
150172
}
151173
catch (PersistenceException ex) {
152174
throw new DataAccessResourceFailureException("Could not obtain JPA EntityManager", ex);
@@ -166,53 +188,113 @@ public static EntityManager getTransactionalEntityManager(EntityManagerFactory e
166188
* @see #getTransactionalEntityManager(javax.persistence.EntityManagerFactory)
167189
* @see JpaTransactionManager
168190
*/
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+
*/
169212
public static EntityManager doGetTransactionalEntityManager(
170-
EntityManagerFactory emf, Map properties) throws PersistenceException {
213+
EntityManagerFactory emf, Map properties, boolean synchronizedWithTransaction) throws PersistenceException {
171214

172215
Assert.notNull(emf, "No EntityManagerFactory specified");
173216

174217
EntityManagerHolder emHolder =
175218
(EntityManagerHolder) TransactionSynchronizationManager.getResource(emf);
176219
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);
183235
}
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();
186257
}
187-
Object transactionData = prepareTransaction(emHolder.getEntityManager(), emf);
188-
TransactionSynchronizationManager.registerSynchronization(
189-
new EntityManagerSynchronization(emHolder, emf, transactionData, false));
190-
emHolder.setSynchronizedWithTransaction(true);
191258
}
192-
return emHolder.getEntityManager();
193259
}
194-
195-
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
260+
else if (!TransactionSynchronizationManager.isSynchronizationActive()) {
196261
// Indicate that we can't obtain a transactional EntityManager.
197262
return null;
198263
}
199264

200265
// Create a new EntityManager for use within the current transaction.
201266
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) {
210287
Object transactionData = prepareTransaction(em, emf);
211288
TransactionSynchronizationManager.registerSynchronization(
212-
new EntityManagerSynchronization(emHolder, emf, transactionData, true));
289+
new TransactionalEntityManagerSynchronization(emHolder, emf, transactionData, true));
213290
emHolder.setSynchronizedWithTransaction(true);
214-
TransactionSynchronizationManager.bindResource(emf, emHolder);
215291
}
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);
216298

217299
return em;
218300
}
@@ -356,7 +438,7 @@ public static void closeEntityManager(EntityManager em) {
356438
* (e.g. when participating in a JtaTransactionManager transaction).
357439
* @see org.springframework.transaction.jta.JtaTransactionManager
358440
*/
359-
private static class EntityManagerSynchronization
441+
private static class TransactionalEntityManagerSynchronization
360442
extends ResourceHolderSynchronization<EntityManagerHolder, EntityManagerFactory>
361443
implements Ordered {
362444

@@ -366,7 +448,7 @@ private static class EntityManagerSynchronization
366448

367449
private final boolean newEntityManager;
368450

369-
public EntityManagerSynchronization(
451+
public TransactionalEntityManagerSynchronization(
370452
EntityManagerHolder emHolder, EntityManagerFactory emf, Object txData, boolean newEm) {
371453
super(emHolder, emf);
372454
this.transactionData = txData;
@@ -381,8 +463,17 @@ public int getOrder() {
381463

382464
@Override
383465
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+
}
384475
try {
385-
resourceHolder.getEntityManager().flush();
476+
em.flush();
386477
}
387478
catch (RuntimeException ex) {
388479
if (this.jpaDialect != null) {
@@ -415,4 +506,26 @@ protected void cleanupResource(EntityManagerHolder resourceHolder, EntityManager
415506
}
416507
}
417508

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+
418531
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.