01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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.toplink;
18:
19: import oracle.toplink.exceptions.TopLinkException;
20: import oracle.toplink.sessions.Session;
21: import oracle.toplink.sessions.UnitOfWork;
22:
23: /**
24: * Convenient abstract implementation of the TopLinkCallback interface,
25: * exposing a UnitOfWork to perform write operations on.
26: *
27: * <p>The exposed UnitOfWork will either be be the active UnitOfWork of
28: * the current transaction, if any, or a temporarily acquired UnitOfWork
29: * that will be committed at the end of the operation.
30: *
31: * @author Juergen Hoeller
32: * @since 1.2
33: * @see #doInUnitOfWork(oracle.toplink.sessions.UnitOfWork)
34: * @see oracle.toplink.sessions.Session#getActiveUnitOfWork()
35: */
36: public abstract class UnitOfWorkCallback implements TopLinkCallback {
37:
38: /**
39: * Determines the UnitOfWork to work on (either the active UnitOfWork or a
40: * temporarily acquired UnitOfWork) and delegates to <code>doInUnitOfWork</code>.
41: * @see #doInUnitOfWork(oracle.toplink.sessions.UnitOfWork)
42: */
43: public final Object doInTopLink(Session session)
44: throws TopLinkException {
45: // Fetch active UnitOfWork or acquire temporary UnitOfWork.
46: UnitOfWork unitOfWork = session.getActiveUnitOfWork();
47: boolean newUnitOfWork = false;
48: if (unitOfWork == null) {
49: unitOfWork = session.acquireUnitOfWork();
50: newUnitOfWork = true;
51: }
52:
53: // Perform callback operation, committing the UnitOfWork unless
54: // it is the active UnitOfWork of an externally managed transaction.
55: try {
56: Object result = doInUnitOfWork(unitOfWork);
57: if (newUnitOfWork) {
58: unitOfWork.commit();
59: }
60: return result;
61: } finally {
62: if (newUnitOfWork) {
63: unitOfWork.release();
64: }
65: }
66: }
67:
68: /**
69: * Called with a UnitOfWork to work on, either the active UnitOfWork or a
70: * temporarily acquired UnitOfWork (as determined by the transaction status).
71: * @param unitOfWork the TopLink UnitOfWork to perform write operations on
72: * @return a result object, or <code>null</code> if none
73: * @throws TopLinkException in case of TopLink errors
74: */
75: protected abstract Object doInUnitOfWork(UnitOfWork unitOfWork)
76: throws TopLinkException;
77:
78: }
|