001: /*
002: * Copyright 2002-2007 the original author or authors.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.springframework.orm.jpa;
018:
019: import java.util.Map;
020:
021: import javax.persistence.EntityExistsException;
022: import javax.persistence.EntityManager;
023: import javax.persistence.EntityManagerFactory;
024: import javax.persistence.EntityNotFoundException;
025: import javax.persistence.NoResultException;
026: import javax.persistence.NonUniqueResultException;
027: import javax.persistence.OptimisticLockException;
028: import javax.persistence.PersistenceException;
029: import javax.persistence.TransactionRequiredException;
030:
031: import org.apache.commons.logging.Log;
032: import org.apache.commons.logging.LogFactory;
033:
034: import org.springframework.beans.factory.BeanFactoryUtils;
035: import org.springframework.beans.factory.ListableBeanFactory;
036: import org.springframework.beans.factory.NoSuchBeanDefinitionException;
037: import org.springframework.dao.DataAccessException;
038: import org.springframework.dao.DataAccessResourceFailureException;
039: import org.springframework.dao.DataIntegrityViolationException;
040: import org.springframework.dao.EmptyResultDataAccessException;
041: import org.springframework.dao.IncorrectResultSizeDataAccessException;
042: import org.springframework.dao.InvalidDataAccessApiUsageException;
043: import org.springframework.jdbc.datasource.DataSourceUtils;
044: import org.springframework.transaction.support.TransactionSynchronizationAdapter;
045: import org.springframework.transaction.support.TransactionSynchronizationManager;
046: import org.springframework.util.Assert;
047: import org.springframework.util.CollectionUtils;
048:
049: /**
050: * Helper class featuring methods for JPA EntityManager handling,
051: * allowing for reuse of EntityManager instances within transactions.
052: * Also provides support for exception translation.
053: *
054: * <p>Mainly intended for internal use within the framework.
055: *
056: * @author Juergen Hoeller
057: * @since 2.0
058: */
059: public abstract class EntityManagerFactoryUtils {
060:
061: /**
062: * Order value for TransactionSynchronization objects that clean up JPA
063: * EntityManagers. Return DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100
064: * to execute EntityManager cleanup before JDBC Connection cleanup, if any.
065: * @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER
066: */
067: public static final int ENTITY_MANAGER_SYNCHRONIZATION_ORDER = DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100;
068:
069: private static final Log logger = LogFactory
070: .getLog(EntityManagerFactoryUtils.class);
071:
072: /**
073: * Find an EntityManagerFactory with the given name in the given
074: * Spring application context (represented as ListableBeanFactory).
075: * <p>The specified unit name will be matched against the configured
076: * peristence unit, provided that a discovered EntityManagerFactory
077: * implements the {@link EntityManagerFactoryInfo} interface. If not,
078: * the persistence unit name will be matched against the Spring bean name,
079: * assuming that the EntityManagerFactory bean names follow that convention.
080: * @param beanFactory the ListableBeanFactory to search
081: * @param unitName the name of the persistence unit (never empty)
082: * @return the EntityManagerFactory
083: * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
084: * @see EntityManagerFactoryInfo#getPersistenceUnitName()
085: */
086: public static EntityManagerFactory findEntityManagerFactory(
087: ListableBeanFactory beanFactory, String unitName)
088: throws NoSuchBeanDefinitionException {
089:
090: Assert.notNull(beanFactory,
091: "ListableBeanFactory must not be null");
092: Assert.hasLength(unitName, "Unit name must not be empty");
093:
094: // See whether we can find an EntityManagerFactory with matching persistence unit name.
095: String[] candidateNames = BeanFactoryUtils
096: .beanNamesForTypeIncludingAncestors(beanFactory,
097: EntityManagerFactory.class);
098: for (String candidateName : candidateNames) {
099: EntityManagerFactory emf = (EntityManagerFactory) beanFactory
100: .getBean(candidateName);
101: if (emf instanceof EntityManagerFactoryInfo) {
102: if (unitName.equals(((EntityManagerFactoryInfo) emf)
103: .getPersistenceUnitName())) {
104: return emf;
105: }
106: }
107: }
108: // No matching persistence unit found - simply take the EntityManagerFactory
109: // with the persistence unit name as bean name (by convention).
110: return (EntityManagerFactory) beanFactory.getBean(unitName,
111: EntityManagerFactory.class);
112: }
113:
114: /**
115: * Obtain a JPA EntityManager from the given factory. Is aware of a
116: * corresponding EntityManager bound to the current thread,
117: * for example when using JpaTransactionManager.
118: * <p>Note: Will return <code>null</code> if no thread-bound EntityManager found!
119: * @param emf EntityManagerFactory to create the EntityManager with
120: * @return the EntityManager, or <code>null</code> if none found
121: * @throws DataAccessResourceFailureException if the EntityManager couldn't be obtained
122: * @see JpaTransactionManager
123: */
124: public static EntityManager getTransactionalEntityManager(
125: EntityManagerFactory emf)
126: throws DataAccessResourceFailureException {
127:
128: return getTransactionalEntityManager(emf, null);
129: }
130:
131: /**
132: * Obtain a JPA EntityManager from the given factory. Is aware of a
133: * corresponding EntityManager bound to the current thread,
134: * for example when using JpaTransactionManager.
135: * <p>Note: Will return <code>null</code> if no thread-bound EntityManager found!
136: * @param emf EntityManagerFactory to create the EntityManager with
137: * @param properties the properties to be passed into the <code>createEntityManager</code>
138: * call (may be <code>null</code>)
139: * @return the EntityManager, or <code>null</code> if none found
140: * @throws DataAccessResourceFailureException if the EntityManager couldn't be obtained
141: * @see JpaTransactionManager
142: */
143: public static EntityManager getTransactionalEntityManager(
144: EntityManagerFactory emf, Map properties)
145: throws DataAccessResourceFailureException {
146: try {
147: return doGetTransactionalEntityManager(emf, properties);
148: } catch (PersistenceException ex) {
149: throw new DataAccessResourceFailureException(
150: "Could not obtain JPA EntityManager", ex);
151: }
152: }
153:
154: /**
155: * Obtain a JPA EntityManager from the given factory. Is aware of a
156: * corresponding EntityManager bound to the current thread,
157: * for example when using JpaTransactionManager.
158: * <p>Same as <code>getEntityManager</code>, but throwing the original PersistenceException.
159: * @param emf EntityManagerFactory to create the EntityManager with
160: * @param properties the properties to be passed into the <code>createEntityManager</code>
161: * call (may be <code>null</code>)
162: * @return the EntityManager, or <code>null</code> if none found
163: * @throws javax.persistence.PersistenceException if the EntityManager couldn't be created
164: * @see #getTransactionalEntityManager(javax.persistence.EntityManagerFactory)
165: * @see JpaTransactionManager
166: */
167: public static EntityManager doGetTransactionalEntityManager(
168: EntityManagerFactory emf, Map properties)
169: throws PersistenceException {
170:
171: Assert.notNull(emf, "No EntityManagerFactory specified");
172:
173: EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
174: .getResource(emf);
175: if (emHolder != null) {
176: if (!emHolder.isSynchronizedWithTransaction()
177: && TransactionSynchronizationManager
178: .isSynchronizationActive()) {
179: // Try to explicitly synchronize the EntityManager itself
180: // with an ongoing JTA transaction, if any.
181: try {
182: emHolder.getEntityManager().joinTransaction();
183: } catch (TransactionRequiredException ex) {
184: logger
185: .debug(
186: "Could not join JTA transaction because none was active",
187: ex);
188: }
189: emHolder.setSynchronizedWithTransaction(true);
190: TransactionSynchronizationManager
191: .registerSynchronization(new EntityManagerSynchronization(
192: emHolder, emf, false));
193: }
194: return emHolder.getEntityManager();
195: }
196:
197: if (!TransactionSynchronizationManager
198: .isSynchronizationActive()) {
199: // Indicate that we can't obtain a transactional EntityManager.
200: return null;
201: }
202:
203: // Create a new EntityManager for use within the current transaction.
204: logger.debug("Opening JPA EntityManager");
205: EntityManager em = (!CollectionUtils.isEmpty(properties) ? emf
206: .createEntityManager(properties) : emf
207: .createEntityManager());
208:
209: if (TransactionSynchronizationManager.isSynchronizationActive()) {
210: logger
211: .debug("Registering transaction synchronization for JPA EntityManager");
212: // Use same EntityManager for further JPA actions within the transaction.
213: // Thread object will get removed by synchronization at transaction completion.
214: emHolder = new EntityManagerHolder(em);
215: emHolder.setSynchronizedWithTransaction(true);
216: TransactionSynchronizationManager
217: .registerSynchronization(new EntityManagerSynchronization(
218: emHolder, emf, true));
219: TransactionSynchronizationManager.bindResource(emf,
220: emHolder);
221: }
222:
223: return em;
224: }
225:
226: /**
227: * Convert the given runtime exception to an appropriate exception from the
228: * <code>org.springframework.dao</code> hierarchy.
229: * Return null if no translation is appropriate: any other exception may
230: * have resulted from user code, and should not be translated.
231: * <p>The most important cases like object not found or optimistic locking
232: * failure are covered here. For more fine-granular conversion, JpaAccessor and
233: * JpaTransactionManager support sophisticated translation of exceptions via a
234: * JpaDialect.
235: * @param ex runtime exception that occured
236: * @return the corresponding DataAccessException instance,
237: * or <code>null</code> if the exception should not be translated
238: */
239: public static DataAccessException convertJpaAccessExceptionIfPossible(
240: RuntimeException ex) {
241: // Following the JPA specification, a persistence provider can also
242: // throw these two exceptions, besides PersistenceException.
243: if (ex instanceof IllegalStateException) {
244: return new InvalidDataAccessApiUsageException(ex
245: .getMessage(), ex);
246: }
247: if (ex instanceof IllegalArgumentException) {
248: return new InvalidDataAccessApiUsageException(ex
249: .getMessage(), ex);
250: }
251:
252: // Check for well-known PersistenceException subclasses.
253: if (ex instanceof EntityNotFoundException) {
254: return new JpaObjectRetrievalFailureException(
255: (EntityNotFoundException) ex);
256: }
257: if (ex instanceof NoResultException) {
258: return new EmptyResultDataAccessException(ex.getMessage(),
259: 1);
260: }
261: if (ex instanceof NonUniqueResultException) {
262: return new IncorrectResultSizeDataAccessException(ex
263: .getMessage(), 1);
264: }
265: if (ex instanceof OptimisticLockException) {
266: return new JpaOptimisticLockingFailureException(
267: (OptimisticLockException) ex);
268: }
269: if (ex instanceof EntityExistsException) {
270: return new DataIntegrityViolationException(ex.getMessage(),
271: ex);
272: }
273: if (ex instanceof TransactionRequiredException) {
274: return new InvalidDataAccessApiUsageException(ex
275: .getMessage(), ex);
276: }
277:
278: // If we have another kind of PersistenceException, throw it.
279: if (ex instanceof PersistenceException) {
280: return new JpaSystemException((PersistenceException) ex);
281: }
282:
283: // If we get here, we have an exception that resulted from user code,
284: // rather than the persistence provider, so we return null to indicate
285: // that translation should not occur.
286: return null;
287: }
288:
289: /**
290: * Callback for resource cleanup at the end of a non-JPA transaction
291: * (e.g. when participating in a JtaTransactionManager transaction).
292: * @see org.springframework.transaction.jta.JtaTransactionManager
293: */
294: private static class EntityManagerSynchronization extends
295: TransactionSynchronizationAdapter {
296:
297: private final EntityManagerHolder entityManagerHolder;
298:
299: private final EntityManagerFactory entityManagerFactory;
300:
301: private final boolean newEntityManager;
302:
303: private boolean holderActive = true;
304:
305: public EntityManagerSynchronization(
306: EntityManagerHolder emHolder, EntityManagerFactory emf,
307: boolean newEntityManager) {
308: this .entityManagerHolder = emHolder;
309: this .entityManagerFactory = emf;
310: this .newEntityManager = newEntityManager;
311: }
312:
313: public int getOrder() {
314: return ENTITY_MANAGER_SYNCHRONIZATION_ORDER;
315: }
316:
317: public void suspend() {
318: if (this .holderActive) {
319: TransactionSynchronizationManager
320: .unbindResource(this .entityManagerFactory);
321: }
322: }
323:
324: public void resume() {
325: if (this .holderActive) {
326: TransactionSynchronizationManager.bindResource(
327: this .entityManagerFactory,
328: this .entityManagerHolder);
329: }
330: }
331:
332: public void beforeCompletion() {
333: if (this .newEntityManager) {
334: TransactionSynchronizationManager
335: .unbindResource(this .entityManagerFactory);
336: this .holderActive = false;
337: this .entityManagerHolder.getEntityManager().close();
338: }
339: }
340:
341: public void afterCompletion(int status) {
342: if (!this .newEntityManager && status != STATUS_COMMITTED) {
343: // Clear all pending inserts/updates/deletes in the EntityManager.
344: // Necessary for pre-bound EntityManagers, to avoid inconsistent state.
345: this .entityManagerHolder.getEntityManager().clear();
346: }
347: this .entityManagerHolder
348: .setSynchronizedWithTransaction(false);
349: }
350: }
351:
352: }
|