KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > orm > jpa > JpaInterceptor


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.orm.jpa;
18
19 import javax.persistence.EntityManager;
20
21 import org.aopalliance.intercept.MethodInterceptor;
22 import org.aopalliance.intercept.MethodInvocation;
23
24 import org.springframework.transaction.support.TransactionSynchronizationManager;
25
26 /**
27  * This interceptor binds a new JPA EntityManager to the thread before a method
28  * call, closing and removing it afterwards in case of any method outcome.
29  * If there already is a pre-bound EntityManager (e.g. from JpaTransactionManager,
30  * or from a surrounding JPA-intercepted method), the interceptor simply participates in it.
31  *
32  * <p>Application code must retrieve a JPA EntityManager via the
33  * <code>EntityManagerFactoryUtils.getEntityManager</code> method or - preferably -
34  * via a shared <code>EntityManager</code> reference, to be able to detect a
35  * thread-bound EntityManager. Typically, the code will look like as follows:
36  *
37  * <pre>
38  * public void doSomeDataAccessAction() {
39  * this.entityManager...
40  * }</pre>
41  *
42  * <p>Note that this interceptor automatically translates PersistenceExceptions,
43  * via delegating to the <code>EntityManagerFactoryUtils.convertJpaAccessException</code>
44  * method that converts them to exceptions that are compatible with the
45  * <code>org.springframework.dao</code> exception hierarchy (like JpaTemplate does).
46  *
47  * <p>This class can be considered a declarative alternative to JpaTemplate's
48  * callback approach. The advantages are:
49  * <ul>
50  * <li>no anonymous classes necessary for callback implementations;
51  * <li>the possibility to throw any application exceptions from within data access code.
52  * </ul>
53  *
54  * <p>The drawback is the dependency on interceptor configuration. However, note
55  * that this interceptor is usually <i>not</i> necessary in scenarios where the
56  * data access code always executes within transactions. A transaction will always
57  * have a thread-bound EntityManager in the first place, so adding this interceptor
58  * to the configuration just adds value when fine-tuning EntityManager settings
59  * like the flush mode - or when relying on exception translation.
60  *
61  * @author Juergen Hoeller
62  * @since 2.0
63  * @see JpaTransactionManager
64  * @see JpaTemplate
65  */

66 public class JpaInterceptor extends JpaAccessor implements MethodInterceptor {
67
68     private boolean exceptionConversionEnabled = true;
69
70
71     /**
72      * Set whether to convert any PersistenceException raised to a Spring DataAccessException,
73      * compatible with the <code>org.springframework.dao</code> exception hierarchy.
74      * <p>Default is "true". Turn this flag off to let the caller receive raw exceptions
75      * as-is, without any wrapping.
76      * @see org.springframework.dao.DataAccessException
77      */

78     public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) {
79         this.exceptionConversionEnabled = exceptionConversionEnabled;
80     }
81
82
83     public Object JavaDoc invoke(MethodInvocation methodInvocation) throws Throwable JavaDoc {
84         // Determine current EntityManager: either the transactional one
85
// managed by the factory or a temporary one for the given invocation.
86
EntityManager em = getTransactionalEntityManager();
87         boolean isNewEm = false;
88         if (em == null) {
89             logger.debug("Creating new EntityManager for JpaInterceptor invocation");
90             em = createEntityManager();
91             isNewEm = true;
92             TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), new EntityManagerHolder(em));
93         }
94
95         try {
96             Object JavaDoc retVal = methodInvocation.proceed();
97             flushIfNecessary(em, !isNewEm);
98             return retVal;
99         }
100         catch (RuntimeException JavaDoc rawException) {
101             if (this.exceptionConversionEnabled) {
102                 // Translation enabled. Translate if we understand the exception.
103
throw translateIfNecessary(rawException);
104             }
105             else {
106                 // Translation not enabled. Don't try to translate.
107
throw rawException;
108             }
109         }
110         finally {
111             if (isNewEm) {
112                 TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
113                 logger.debug("Closing new EntityManager after JpaInterceptor invocation");
114                 em.close();
115             }
116         }
117     }
118
119 }
120
Popular Tags