KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > orm > hibernate > HibernateInterceptor


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.hibernate;
18
19 import net.sf.hibernate.FlushMode;
20 import net.sf.hibernate.HibernateException;
21 import net.sf.hibernate.Session;
22 import org.aopalliance.intercept.MethodInterceptor;
23 import org.aopalliance.intercept.MethodInvocation;
24
25 import org.springframework.transaction.support.TransactionSynchronizationManager;
26
27 /**
28  * This interceptor binds a new Hibernate Session to the thread before a method
29  * call, closing and removing it afterwards in case of any method outcome.
30  * If there already is a pre-bound Session (e.g. from HibernateTransactionManager,
31  * or from a surrounding Hibernate-intercepted method), the interceptor simply
32  * participates in it.
33  *
34  * <p>Application code must retrieve a Hibernate Session via the
35  * <code>SessionFactoryUtils.getSession</code> method, to be able to detect a
36  * thread-bound Session. It is preferable to use <code>getSession</code> with
37  * allowCreate=false, if the code relies on the interceptor to provide proper
38  * Session handling. Typically, the code will look like as follows:
39  *
40  * <pre>
41  * public void doSomeDataAccessAction() {
42  * Session session = SessionFactoryUtils.getSession(this.sessionFactory, false);
43  * try {
44  * ...
45  * }
46  * catch (HibernateException ex) {
47  * throw SessionFactoryUtils.convertHibernateAccessException(ex);
48  * }
49  * }</pre>
50  *
51  * Note that the application must care about handling HibernateExceptions itself,
52  * preferably via delegating to the <code>SessionFactoryUtils.convertHibernateAccessException</code>
53  * method that converts them to exceptions that are compatible with the
54  * <code>org.springframework.dao</code> exception hierarchy (like HibernateTemplate does).
55  *
56  * <p>Unfortunately, this interceptor cannot convert checked HibernateExceptions
57  * to unchecked dao ones transparently. The intercepted method would have to declare
58  * the checked HibernateException - thus the caller would still have to catch or
59  * rethrow it, even if it will never be thrown if intercepted. Any such exception
60  * will nevertheless get converted by default.
61  *
62  * <p>This class can be considered a declarative alternative to HibernateTemplate's
63  * callback approach. The advantages are:
64  * <ul>
65  * <li>no anonymous classes necessary for callback implementations;
66  * <li>the possibility to throw any application exceptions from within data access code.
67  * </ul>
68  *
69  * <p>The drawbacks are:
70  * <ul>
71  * <li>the dependency on interceptor configuration;
72  * <li>the delegating try/catch blocks.
73  * </ul>
74  *
75  * <p>Note: Spring's Hibernate support in this package requires Hibernate 2.1.
76  * Dedicated Hibernate3 support can be found in a separate package:
77  * <code>org.springframework.orm.hibernate3</code>.
78  *
79  * @author Juergen Hoeller
80  * @since 13.06.2003
81  * @see SessionFactoryUtils#getSession
82  * @see HibernateTransactionManager
83  * @see HibernateTemplate
84  */

85 public class HibernateInterceptor extends HibernateAccessor implements MethodInterceptor {
86
87     private boolean exceptionConversionEnabled = true;
88
89
90     /**
91      * Set whether to convert any HibernateException raised to a Spring DataAccessException,
92      * compatible with the <code>org.springframework.dao</code> exception hierarchy.
93      * <p>Default is "true". Turn this flag off to let the caller receive raw exceptions
94      * as-is, without any wrapping. Note that this means that the DAO methods will have
95      * to declare the checked HibernateException, and callers will be forced to handle it.
96      * @see org.springframework.dao.DataAccessException
97      */

98     public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) {
99         this.exceptionConversionEnabled = exceptionConversionEnabled;
100     }
101
102
103     public Object JavaDoc invoke(MethodInvocation methodInvocation) throws Throwable JavaDoc {
104         Session session = getSession();
105         boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory());
106
107         if (existingTransaction) {
108             logger.debug("Found thread-bound Session for HibernateInterceptor");
109         }
110         else {
111             TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
112         }
113
114         FlushMode previousFlushMode = null;
115         try {
116             previousFlushMode = applyFlushMode(session, existingTransaction);
117             Object JavaDoc retVal = methodInvocation.proceed();
118             flushIfNecessary(session, existingTransaction);
119             return retVal;
120         }
121         catch (HibernateException ex) {
122             if (this.exceptionConversionEnabled) {
123                 throw convertHibernateAccessException(ex);
124             }
125             else {
126                 throw ex;
127             }
128         }
129         finally {
130             if (existingTransaction) {
131                 logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
132                 if (previousFlushMode != null) {
133                     session.setFlushMode(previousFlushMode);
134                 }
135             }
136             else {
137                 TransactionSynchronizationManager.unbindResource(getSessionFactory());
138                 SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
139             }
140         }
141     }
142
143     /**
144      * Return a Session for use by this interceptor.
145      * @see SessionFactoryUtils#getSession
146      */

147     protected Session getSession() {
148         return SessionFactoryUtils.getSession(
149                 getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
150     }
151
152 }
153
Popular Tags