View Javadoc

1   /***
2    * @(#)IbatisServiceImpl.java
3    * 
4    * JFoxSOAF, Service-Oriented Application Framework
5    * 
6    * Copyright(c) JFoxSOAF Team
7    * 
8    * Licensed under the GNU LGPL, Version 2.1 (the "License"); 
9    * you may not use this file except in compliance with the License. 
10   * You may obtain a copy of the License at  
11   * 
12   * http://www.gnu.org/copyleft/lesser.html
13   * 
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, 
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
17   * See the License for the specific language governing permissions and 
18   * limitations under the License. 
19   * 
20   * For more information, please visit:
21   * http://www.jfox.cn/confluence/display/JFoxSOAF/Home
22   * http://www.huihoo.org/jfox/jfoxsoaf
23   */
24  
25  package org.huihoo.jfox.soaf.services.persistence;
26  
27  import java.io.Reader;
28  import java.sql.SQLException;
29  import java.util.List;
30  import java.util.Map;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.huihoo.jfox.soaf.exception.DAOException;
35  import org.huihoo.jfox.soaf.exception.IbatisConfigurationException;
36  import org.picocontainer.Startable;
37  
38  import com.ibatis.common.resources.Resources;
39  import com.ibatis.common.util.PaginatedList;
40  import com.ibatis.dao.client.DaoManager;
41  import com.ibatis.dao.client.DaoManagerBuilder;
42  import com.ibatis.sqlmap.client.SqlMapClient;
43  import com.ibatis.sqlmap.client.SqlMapClientBuilder;
44  import com.ibatis.sqlmap.client.SqlMapSession;
45  import com.ibatis.sqlmap.client.event.RowHandler;
46  
47  /***
48   * <p>
49   * Ibatis persistence service wrapper.
50   * </p>
51   * 
52   * @author <a href="mailto:founder_chen@yahoo.com.cn">Peter Cheng </a>
53   * @version $Revision: 1.6 $ $Date: 2005/01/17 14:18:14 $
54   * @version Revision: 1.0
55   */
56  
57  public class IbatisServiceImpl implements IbatisService, Startable {
58      
59      private final Log logger = LogFactory.getLog(getClass());
60  
61      private static final String IBATIS_DAO_RESOURCE = "ibatis-dao.xml";
62  
63      private static final String IBATIS_SQLMAP_RESOURCE = "ibatis-sqlmap-config.xml";
64  
65      private DaoManager daoManager;
66  
67      private SqlMapClient sqlMapClient;
68  
69      private SqlMapSession session;
70  
71      /***
72       * Defalut Constructor.
73       */
74      public IbatisServiceImpl() {
75      }
76  
77      /***
78       * @see org.huihoo.jfox.soaf.services.persistence.IbatisService#getDaoManager()
79       */
80      public DaoManager getDaoManager() {
81          return this.daoManager;
82      }
83  
84      private SqlMapClient getSqlMapClient() {
85          return this.sqlMapClient;
86      }
87  
88      /***
89       * Returns a single threaded SqlMapSession implementation for use by one
90       * user.
91       * 
92       * @see org.huihoo.jfox.soaf.services.persistence.IbatisService#openSession()
93       */
94      public SqlMapSession openSession() throws SQLException {
95          if (session != null) {
96              session = getSqlMapClient().openSession();
97              session.startTransaction();
98          }
99          return session;
100     }
101 
102     /***
103      * @see org.huihoo.jfox.soaf.services.persistence.IbatisService#commit()
104      */
105     public void commit() throws SQLException {
106         if (session != null) {
107             session.commitTransaction();
108         }
109     }
110 
111     /***
112      * @see org.huihoo.jfox.soaf.services.persistence.IbatisService#closeSession()
113      */
114     public void closeSession() throws SQLException {
115         if (session != null) {
116             session.endTransaction();
117             session.close();
118             session = null;
119         }
120     }
121 
122     /***
123      * @see org.picocontainer.Startable#start()
124      */
125     public void start() {
126         try {
127             Reader reader = Resources.getResourceAsReader(IBATIS_DAO_RESOURCE);
128             Reader sqlMapClientReader = Resources
129                     .getResourceAsReader(IBATIS_SQLMAP_RESOURCE);
130             daoManager = DaoManagerBuilder.buildDaoManager(reader);
131             sqlMapClient = SqlMapClientBuilder
132                     .buildSqlMapClient(sqlMapClientReader);
133         } catch (Exception e) {
134             throw new IbatisConfigurationException(
135                     "Failed to initialize Ibatis DaoConfig.  Cause: " + e);
136         }
137         logger.info("Start ibatis service successful.");
138     }
139 
140     /***
141      * @see org.picocontainer.Startable#stop()
142      */
143     public void stop() {
144     }
145     
146     /***
147      * Executes a mapped SQL INSERT statement. Insert is a bit different from
148      * other update methods, as it provides facilities for returning the primary
149      * key of the newly inserted row (rather than the effected rows). This
150      * functionality is of course optional.
151      * 
152      * @param id
153      * @param parameterObject
154      * @return The primary key of the newly inserted row. This might be
155      *         automatically generated by the RDBMS, or selected from a sequence
156      *         table or other source.
157      * @throws SQLException
158      * @throws DAOException
159      */
160     public Object insert(String id, Object parameterObject)
161             throws SQLException, DAOException {
162         SqlMapSession session;
163         Object object;
164         try {
165             session = openSession();
166             object = session.insert(id, parameterObject);
167             commit();
168         } catch (Exception e) {
169             throw new DAOException("Failed to insert - id [" + id
170                     + "], parameterObject [" + parameterObject + "]. Cause: "
171                     + e, e);
172         } finally {
173             session = null;
174             closeSession();
175         }
176         return object;
177     }
178 
179     /***
180      * Executes a mapped SQL UPDATE statement. Update can also be used for any
181      * other update statement type, such as inserts and deletes. Update returns
182      * the number of rows effected.
183      * 
184      * @param id
185      * @param parameterObject
186      * @return The number of rows effected.
187      * @throws SQLException
188      * @throws DAOException
189      */
190     public int update(String id, Object parameterObject) throws SQLException,
191             DAOException {
192         SqlMapSession session;
193         int rowsNum;
194         try {
195             session = openSession();
196             rowsNum = session.update(id, parameterObject);
197             commit();
198         } catch (Exception e) {
199             throw new DAOException("Failed to update - id [" + id
200                     + "], parameterObject [" + parameterObject + "]. Cause: "
201                     + e, e);
202         } finally {
203             session = null;
204             closeSession();
205         }
206         return rowsNum;
207     }
208 
209     /***
210      * Executes a mapped SQL DELETE statement. Delete returns the number of rows
211      * effected.
212      * 
213      * @param id
214      * @param parameterObject
215      * @return The number of rows effected
216      * @throws SQLException
217      * @throws DAOException
218      */
219     public int delete(String id, Object parameterObject) throws SQLException,
220             DAOException {
221         SqlMapSession session;
222         int rowsNum;
223         try {
224             session = openSession();
225             rowsNum = session.delete(id, parameterObject);
226             commit();
227         } catch (Exception e) {
228             throw new DAOException("Failed to delete - id [" + id
229                     + "], parameterObject [" + parameterObject + "]. Cause: "
230                     + e, e);
231         } finally {
232             session = null;
233             closeSession();
234         }
235         return rowsNum;
236     }
237 
238     /***
239      * Executes a mapped SQL SELECT statement that returns data to populate a
240      * single object instance. <p/>The parameter object is generally used to
241      * supply the input data for the WHERE clause parameter(s) of the SELECT
242      * statement.
243      * 
244      * @param id The name of the statement to execute.
245      * @param parameterObject The parameter object (e.g. JavaBean, Map, XML
246      *            etc.).
247      * @return The single result object populated with the result set data.
248      */
249     public Object queryForObject(String id, Object parameterObject)
250             throws SQLException, DAOException {
251         SqlMapSession session;
252         Object object;
253         try {
254             session = openSession();
255             object = session.queryForObject(id, parameterObject);
256             commit();
257         } catch (Exception e) {
258             throw new DAOException("Failed to execute queryForObject - id ["
259                     + id + "], parameterObject [" + parameterObject
260                     + "].  Cause: " + e, e);
261         } finally {
262             session = null;
263             closeSession();
264         }
265         return object;
266     }
267 
268     /***
269      * Executes a mapped SQL SELECT statement that returns data to populate the
270      * supplied result object.
271      * 
272      * @param id
273      * @param parameterObject
274      * @param resultObject
275      * @return The single result object as supplied by the resultObject
276      *         parameter, populated with the result set data.
277      * @throws SQLException
278      * @throws DAOException
279      */
280     public Object queryForObject(String id, Object parameterObject,
281             Object resultObject) throws SQLException, DAOException {
282         SqlMapSession session;
283         Object object;
284         try {
285             session = openSession();
286             object = session.queryForObject(id, parameterObject, resultObject);
287             commit();
288         } catch (Exception e) {
289             throw new DAOException("Failed to execute queryForObject - id ["
290                     + id + "], parameterObject [" + parameterObject
291                     + "].  Cause: " + e, e);
292         } finally {
293             session = null;
294             closeSession();
295         }
296         return object;
297     }
298 
299     /***
300      * Executes a mapped SQL SELECT statement that returns data to populate a
301      * number of result objects.
302      * 
303      * @param id
304      * @param parameterObject
305      * @return A List of result objects.
306      * @throws SQLException
307      * @throws DAOException
308      */
309     public List queryForList(String id, Object parameterObject)
310             throws SQLException, DAOException {
311         SqlMapSession session;
312         List list;
313         try {
314             session = openSession();
315             list = session.queryForList(id, parameterObject);
316             commit();
317         } catch (Exception e) {
318             throw new DAOException("Failed to queryForList - id [" + id
319                     + "], parameterObject [" + parameterObject + "].  Cause: "
320                     + e, e);
321         } finally {
322             session = null;
323             closeSession();
324         }
325         return list;
326     }
327 
328     /***
329      * Executes a mapped SQL SELECT statement that returns data to populate a
330      * number of result objects within a certain range.
331      * 
332      * @param id
333      * @param parameterObject
334      * @param skip
335      * @param max
336      * @return A List of result objects.
337      * @throws SQLException
338      * @throws DAOException
339      */
340     public List queryForList(String id, Object parameterObject, int skip,
341             int max) throws SQLException, DAOException {
342         SqlMapSession session;
343         List list;
344         try {
345             session = openSession();
346             list = session.queryForList(id, parameterObject, skip, max);
347             commit();
348         } catch (Exception e) {
349             throw new DAOException("Failed to queryForList - id [" + id
350                     + "], parameterObject [" + parameterObject + "], skip ["
351                     + skip + "], max [" + max + "].  Cause: " + e, e);
352         } finally {
353             session = null;
354             closeSession();
355         }
356         return list;
357     }
358 
359     /***
360      * Executes a mapped SQL SELECT statement that returns a number of result
361      * objects that will be handled one at a time by a RowHandler.
362      * 
363      * @param id
364      * @param parameterObject
365      * @param rowHandler
366      * @throws SQLException
367      * @throws DAOException
368      */
369     public void queryWithRowHandler(String id, Object parameterObject,
370             RowHandler rowHandler) throws SQLException, DAOException {
371         SqlMapSession session;
372         List list;
373         try {
374             session = openSession();
375             session.queryWithRowHandler(id, parameterObject, rowHandler);
376             commit();
377         } catch (Exception e) {
378             throw new DAOException("Failed to queryForList - id [" + id
379                     + "], parameterObject [" + parameterObject
380                     + "], rowHandler [ " + rowHandler + "].  Cause: " + e, e);
381         } finally {
382             session = null;
383             closeSession();
384         }
385     }
386 
387     /***
388      * Executes a mapped SQL SELECT statement that returns data to populate a
389      * number of result objects a page at a time.
390      * 
391      * @param id
392      * @param parameterObject
393      * @param pageSize
394      * @return A PaginatedList of result objects.
395      * @throws SQLException
396      * @throws DAOException
397      */
398     public PaginatedList queryForPaginatedList(String id,
399             Object parameterObject, int pageSize) throws SQLException,
400             DAOException {
401         SqlMapSession session;
402         PaginatedList list;
403         try {
404             session = openSession();
405             list = session.queryForPaginatedList(id, parameterObject, pageSize);
406             commit();
407         } catch (Exception e) {
408             throw new DAOException("Failed to queryForPaginatedList - id ["
409                     + id + "], parameterObject [" + parameterObject
410                     + "], pageSize [" + pageSize + "].  Cause: " + e, e);
411         } finally {
412             session = null;
413             closeSession();
414         }
415         return list;
416     }
417 
418     /***
419      * Executes a mapped SQL SELECT statement that returns data to populate a
420      * number of result objects that will be keyed into a Map.
421      * 
422      * @param id
423      * @param parameterObject
424      * @param keyProp
425      * @return A Map keyed by keyProp with values being the result object
426      *         instance.
427      * @throws SQLException
428      * @throws DAOException
429      */
430     public Map queryForMap(String id, Object parameterObject, String keyProp)
431             throws SQLException, DAOException {
432         SqlMapSession session;
433         Map map;
434         try {
435             session = openSession();
436             map = session.queryForMap(id, parameterObject, keyProp);
437             commit();
438         } catch (Exception e) {
439             throw new DAOException("Failed to queryForMap - id [" + id
440                     + "], parameterObject [" + parameterObject + "], keyProp ["
441                     + keyProp + "].  Cause: " + e, e);
442         } finally {
443             session = null;
444             closeSession();
445         }
446         return map;
447     }
448 
449     /***
450      * Executes a mapped SQL SELECT statement that returns data to populate a
451      * number of result objects from which one property will be keyed into a
452      * Map.
453      * 
454      * @param id
455      * @param parameterObject
456      * @param keyProp
457      * @param valueProp
458      * @return A Map keyed by keyProp with values of valueProp.
459      * @throws SQLException
460      * @throws DAOException
461      */
462     public Map queryForMap(String id, Object parameterObject, String keyProp,
463             String valueProp) throws SQLException, DAOException {
464         SqlMapSession session;
465         Map map;
466         try {
467             session = openSession();
468             map = session.queryForMap(id, parameterObject, keyProp, valueProp);
469             commit();
470         } catch (Exception e) {
471             throw new DAOException("Failed to queryForMap - id [" + id
472                     + "], parameterObject [" + parameterObject + "], keyProp ["
473                     + keyProp + "], valueProp [" + valueProp + "].  Cause: "
474                     + e, e);
475         } finally {
476             session = null;
477             closeSession();
478         }
479         return map;
480     }
481     
482 }