KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > orm > ojb > PersistenceBrokerTemplate


1 /*
2  * Copyright 2002-2005 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.ojb;
18
19 import java.sql.SQLException JavaDoc;
20 import java.util.Collection JavaDoc;
21 import java.util.Iterator JavaDoc;
22
23 import org.apache.ojb.broker.Identity;
24 import org.apache.ojb.broker.PBKey;
25 import org.apache.ojb.broker.PersistenceBroker;
26 import org.apache.ojb.broker.PersistenceBrokerException;
27 import org.apache.ojb.broker.accesslayer.LookupException;
28 import org.apache.ojb.broker.query.Query;
29
30 import org.springframework.dao.DataAccessException;
31 import org.springframework.dao.DataAccessResourceFailureException;
32 import org.springframework.orm.ObjectRetrievalFailureException;
33
34 /**
35  * Helper class that simplifies OJB PersistenceBroker data access code,
36  * and converts PersistenceBrokerExceptions into Spring DataAccessExceptions,
37  * following the <code>org.springframework.dao</code> exception hierarchy.
38  *
39  * <p>The central method is "execute", supporting OJB code implementing
40  * the PersistenceBrokerCallback interface. It provides PersistenceBroker handling
41  * such that neither the PersistenceBrokerCallback implementation nor the calling
42  * code needs to explicitly care about retrieving/closing PersistenceBrokers,
43  * or handling OJB lifecycle exceptions.
44  *
45  * <p>Typically used to implement data access or business logic services that
46  * use OJB within their implementation but are OJB-agnostic in their interface.
47  * The latter or code calling the latter only have to deal with business objects,
48  * query objects, and <code>org.springframework.dao</code> exceptions.
49  *
50  * <p>Note that operations that return an Iterator (that is,
51  * <code>getIteratorByQuery</code> and <code>getReportQueryIteratorByQuery</code>)
52  * are supposed to be used within Spring-managed transactions
53  * (with PersistenceBrokerTransactionManager or JtaTransactionManager).
54  * Else, the Iterator won't be able to read results from its ResultSet anymore,
55  * as the underlying PersistenceBroker will already have been closed.
56  *
57  * @author Juergen Hoeller
58  * @since 1.1
59  * @see #setPbKey
60  * @see PersistenceBrokerCallback
61  * @see org.apache.ojb.broker.PersistenceBroker
62  * @see #getIteratorByQuery
63  * @see #getReportQueryIteratorByQuery
64  * @see PersistenceBrokerTransactionManager
65  * @see org.springframework.transaction.jta.JtaTransactionManager
66  */

67 public class PersistenceBrokerTemplate extends OjbAccessor implements PersistenceBrokerOperations {
68
69     private boolean allowCreate = true;
70
71
72     /**
73      * Create a new PersistenceBrokerTemplate,
74      * using the default connection configured for OJB.
75      * Can be further configured via bean properties.
76      */

77     public PersistenceBrokerTemplate() {
78     }
79
80     /**
81      * Create a new PersistenceBrokerTemplate,
82      * using the default connection configured for OJB.
83      * @param allowCreate if a non-transactional PersistenceBroker should be created
84      * when no transactional PersistenceBroker can be found for the current thread
85      */

86     public PersistenceBrokerTemplate(boolean allowCreate) {
87         setAllowCreate(allowCreate);
88         afterPropertiesSet();
89     }
90
91     /**
92      * Create a new PersistenceBrokerTemplate.
93      * @param pbKey the PBKey of the PersistenceBroker configuration to use
94      */

95     public PersistenceBrokerTemplate(PBKey pbKey) {
96         setPbKey(pbKey);
97         afterPropertiesSet();
98     }
99
100     /**
101      * Create a new PersistenceBrokerTemplate.
102      * @param pbKey the PBKey of the PersistenceBroker configuration to use
103      * @param allowCreate if a new PersistenceBroker should be created
104      * if no thread-bound found
105      */

106     public PersistenceBrokerTemplate(PBKey pbKey, boolean allowCreate) {
107         setPbKey(pbKey);
108         setAllowCreate(allowCreate);
109         afterPropertiesSet();
110     }
111
112     /**
113      * Set if a new PersistenceBroker should be created when no transactional
114      * PersistenceBroker can be found for the current thread.
115      * <p>JdoTemplate is aware of a corresponding PersistenceBroker bound to the
116      * current thread, for example when using PersistenceBrokerTransactionManager.
117      * If allowCreate is true, a new non-transactional PersistenceManager will be
118      * created if none found, which needs to be closed at the end of the operation.
119      * If false, an IllegalStateException will get thrown in this case.
120      * @see OjbFactoryUtils#getPersistenceBroker(org.apache.ojb.broker.PBKey, boolean)
121      */

122     public void setAllowCreate(boolean allowCreate) {
123         this.allowCreate = allowCreate;
124     }
125
126     /**
127      * Return if a new PersistenceBroker should be created if no thread-bound found.
128      */

129     public boolean isAllowCreate() {
130         return allowCreate;
131     }
132
133
134     public Object JavaDoc execute(PersistenceBrokerCallback action) throws DataAccessException {
135         PersistenceBroker pb = getPersistenceBroker();
136         try {
137             return action.doInPersistenceBroker(pb);
138         }
139         catch (PersistenceBrokerException ex) {
140             throw convertOjbAccessException(ex);
141         }
142         catch (LookupException ex) {
143             throw new DataAccessResourceFailureException("Could not retrieve resource", ex);
144         }
145         catch (SQLException JavaDoc ex) {
146             throw convertJdbcAccessException(ex);
147         }
148         catch (RuntimeException JavaDoc ex) {
149             // callback code threw application exception
150
throw ex;
151         }
152         finally {
153             releasePersistenceBroker(pb);
154         }
155     }
156
157     public Collection JavaDoc executeFind(PersistenceBrokerCallback action) throws DataAccessException {
158         return (Collection JavaDoc) execute(action);
159     }
160
161
162     public Object JavaDoc getObjectById(final Class JavaDoc entityClass, final Object JavaDoc idValue) throws DataAccessException {
163         return execute(new PersistenceBrokerCallback() {
164             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
165                 Identity id = pb.serviceIdentity().buildIdentity(entityClass, idValue);
166                 Object JavaDoc result = pb.getObjectByIdentity(id);
167                 if (result == null) {
168                     throw new ObjectRetrievalFailureException(entityClass, idValue);
169                 }
170                 return result;
171             }
172         });
173     }
174
175     public Object JavaDoc getObjectByQuery(final Query query) throws DataAccessException {
176         return execute(new PersistenceBrokerCallback() {
177             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
178                 return pb.getObjectByQuery(query);
179             }
180         });
181     }
182
183     public Collection JavaDoc getCollectionByQuery(final Query query) throws DataAccessException {
184         return executeFind(new PersistenceBrokerCallback() {
185             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
186                 return pb.getCollectionByQuery(query);
187             }
188         });
189     }
190
191     public Iterator JavaDoc getIteratorByQuery(final Query query) throws DataAccessException {
192         return (Iterator JavaDoc) execute(new PersistenceBrokerCallback() {
193             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
194                 return pb.getIteratorByQuery(query);
195             }
196         });
197     }
198
199     public Iterator JavaDoc getReportQueryIteratorByQuery(final Query query) {
200         return (Iterator JavaDoc) execute(new PersistenceBrokerCallback() {
201             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
202                 return pb.getReportQueryIteratorByQuery(query);
203             }
204         });
205     }
206
207     public int getCount(final Query query) throws DataAccessException {
208         Integer JavaDoc count = (Integer JavaDoc) execute(new PersistenceBrokerCallback() {
209             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
210                 return new Integer JavaDoc(pb.getCount(query));
211             }
212         });
213         return count.intValue();
214     }
215
216     public void removeFromCache(final Object JavaDoc entityOrId) throws DataAccessException {
217         execute(new PersistenceBrokerCallback() {
218             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
219                 pb.removeFromCache(entityOrId);
220                 return null;
221             }
222         });
223     }
224
225     public void clearCache() throws DataAccessException {
226         execute(new PersistenceBrokerCallback() {
227             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
228                 pb.clearCache();
229                 return null;
230             }
231         });
232     }
233
234     public void store(final Object JavaDoc entity) throws DataAccessException {
235         execute(new PersistenceBrokerCallback() {
236             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
237                 pb.store(entity);
238                 return null;
239             }
240         });
241     }
242
243     public void delete(final Object JavaDoc entity) throws DataAccessException {
244         execute(new PersistenceBrokerCallback() {
245             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
246                 pb.delete(entity);
247                 return null;
248             }
249         });
250     }
251
252     public void deleteByQuery(final Query query) throws DataAccessException {
253         execute(new PersistenceBrokerCallback() {
254             public Object JavaDoc doInPersistenceBroker(PersistenceBroker pb) throws PersistenceBrokerException {
255                 pb.deleteByQuery(query);
256                 return null;
257             }
258         });
259     }
260
261
262     /**
263      * Get an OJB PersistenceBroker for the PBKey of this template.
264      * <p>Default implementation delegates to OjbFactoryUtils.
265      * Can be overridden in subclasses, e.g. for testing purposes.
266      * @return the PersistenceBroker
267      * @throws DataAccessResourceFailureException if the PersistenceBroker couldn't be created
268      * @throws IllegalStateException if no thread-bound PersistenceBroker found and allowCreate false
269      * @see #setJcdAlias
270      * @see #setPbKey
271      * @see #setAllowCreate
272      * @see OjbFactoryUtils#getPersistenceBroker(PBKey, boolean)
273      */

274     protected PersistenceBroker getPersistenceBroker()
275             throws DataAccessResourceFailureException, IllegalStateException JavaDoc {
276
277         return OjbFactoryUtils.getPersistenceBroker(getPbKey(), isAllowCreate());
278     }
279
280     /**
281      * Close the given PersistenceBroker, created for the PBKey of this
282      * template, if it isn't bound to the thread.
283      * <p>Default implementation delegates to OjbFactoryUtils.
284      * Can be overridden in subclasses, e.g. for testing purposes.
285      * @param pb PersistenceBroker to close
286      * @see #setJcdAlias
287      * @see #setPbKey
288      * @see OjbFactoryUtils#releasePersistenceBroker
289      */

290     protected void releasePersistenceBroker(PersistenceBroker pb) {
291         OjbFactoryUtils.releasePersistenceBroker(pb, getPbKey());
292     }
293
294
295 }
296
Popular Tags