KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > genimen > djeneric > repository > rdbms > RdbmsDjenericObject


1 /*
2  Copyright (c) 2001-2005 by Genimen BV (www.genimen.com) All rights reserved.
3  Redistribution and use in source and binary forms, with or without modification, is permitted
4  provided that the following conditions are met:
5  - Redistributions of source code must retain the above copyright notice, this list of conditions
6  and the following disclaimer.
7  - Redistributions in binary form must reproduce the above copyright notice, this list of
8  conditions and the following disclaimer in the documentation and/or other materials
9  provided with the distribution.
10  - All advertising materials mentioning features or use of this software must display the
11  following acknowledgment: "This product includes Djeneric."
12  - Products derived from this software may not be called "Djeneric" nor may
13  "Djeneric" appear in their names without prior written permission of Genimen BV.
14  - Redistributions of any form whatsoever must retain the following acknowledgment: "This
15  product includes Djeneric."
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
17  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  ARE DISCLAIMED. IN NO EVENT SHALL GENIMEN BV, DJENERIC.ORG,
20  OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */

28 package com.genimen.djeneric.repository.rdbms;
29
30 import java.io.IOException JavaDoc;
31 import java.math.BigDecimal JavaDoc;
32 import java.sql.ResultSet JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.sql.Types JavaDoc;
35
36 import com.genimen.djeneric.language.Messages;
37 import com.genimen.djeneric.repository.DjDomain;
38 import com.genimen.djeneric.repository.DjExtent;
39 import com.genimen.djeneric.repository.DjObject;
40 import com.genimen.djeneric.repository.DjPersistenceManager;
41 import com.genimen.djeneric.repository.DjProperty;
42 import com.genimen.djeneric.repository.DjSession;
43 import com.genimen.djeneric.repository.exceptions.CanNotDeleteException;
44 import com.genimen.djeneric.repository.exceptions.DjenericException;
45 import com.genimen.djeneric.repository.exceptions.NotPersistedException;
46 import com.genimen.djeneric.repository.exceptions.ObjectNotDefinedException;
47 import com.genimen.djeneric.repository.exceptions.PersistenceException;
48 import com.genimen.djeneric.repository.exceptions.PropertyFormatException;
49
50 /**
51  * Description of the Class
52  *
53  *@author Wido Riezebos
54  *@created 27 mei 2002
55  */

56 public class RdbmsDjenericObject extends DjObject
57 {
58   /**
59    * Constructor for the RdbmsDjenericObject object
60    *
61    *@param session Description of the Parameter
62    *@param extent Description of the Parameter
63    *@exception DjenericException Description of the Exception
64    */

65   protected RdbmsDjenericObject(DjSession session, DjExtent extent) throws DjenericException
66   {
67     super(session, extent);
68   }
69
70   /**
71    * Constructor for the RdbmsDjenericObject object
72    *
73    *@param session Description of the Parameter
74    *@param objectType Description of the Parameter
75    *@exception DjenericException Description of the Exception
76    */

77   protected RdbmsDjenericObject(DjSession session, String JavaDoc objectType) throws DjenericException
78   {
79     super(session, objectType);
80   }
81
82   ///////////////////////////////////////////////////////////////////////////////////////////
83
////////////////////// DML STUFF
84

85   /**
86    * Returns the rdbmsSession of the RdbmsDjenericObject object
87    *
88    *@return The rdbmsSession value
89    */

90   protected RdbmsSession getRdbmsSession()
91   {
92     return (RdbmsSession) getSession();
93   }
94
95   /**
96    * Sets the originalWhereParameters of the RdbmsDjenericObject object
97    *
98    *@param stmt The new originalWhereParameters value
99    *@exception DjenericException Description of the Exception
100    */

101   protected void setOriginalWhereParameters(SqlStatement stmt) throws DjenericException
102   {
103     try
104     {
105       Object JavaDoc[] originalPropertyValues = getOriginalPropertyValues();
106       for (int i = 0; i < getExtent().getPropertyCount(); i++)
107       {
108         if (originalPropertyValues[i] == null) continue;
109
110         DjProperty col = getExtent().getProperty(i);
111         String JavaDoc paramName = "org_" + col.getName();
112
113         if (col.isMappedToLong())
114         // ignore blob fields; databases usually do not support where clauses with blobs in'em
115
continue;
116         else if (col.getTypeCode() == DjDomain.STRING_TYPE) stmt.setString(paramName,
117                                                                            (String JavaDoc) originalPropertyValues[i]);
118         else if (col.getTypeCode() == DjDomain.INT_TYPE) stmt.setInt(paramName, ((Integer JavaDoc) originalPropertyValues[i])
119             .intValue());
120         else if (col.getTypeCode() == DjDomain.LONG_TYPE) stmt.setLong(paramName, ((Long JavaDoc) originalPropertyValues[i])
121             .longValue());
122         else if (col.getTypeCode() == DjDomain.DATE_TYPE)
123         {
124           // Be careful not to loose milli's
125
if (originalPropertyValues[i] instanceof java.sql.Timestamp JavaDoc) stmt
126               .setTimestamp(paramName, (java.sql.Timestamp JavaDoc) originalPropertyValues[i]);
127           else stmt.setTimestamp(paramName, new java.sql.Timestamp JavaDoc(((java.util.Date JavaDoc) originalPropertyValues[i])
128               .getTime()));
129         }
130         else if (col.getTypeCode() == DjDomain.BIGDECIMAL_TYPE) stmt
131             .setBigDecimal(paramName, (BigDecimal JavaDoc) originalPropertyValues[i]);
132         else
133         // ignore blob fields; databases usually do not support where clauses with blobs in'em
134
if (col.getTypeCode() == DjDomain.BYTE_TYPE) continue;
135         else throw new PersistenceException(Messages.getString("RdbmsDjenericObject.UnknownColumnType", col.getType()),
136             this);
137       }
138     }
139     catch (SQLException JavaDoc x)
140     {
141       throw new DjenericException(x);
142     }
143   }
144
145   /**
146    * Sets the keyPropertyParameter of the RdbmsDjenericObject object
147    *
148    *@param stmt The new keyPropertyParameter value
149    *@exception ObjectNotDefinedException Description of the Exception
150    *@exception PropertyFormatException Description of the Exception
151    *@exception DjenericException Description of the Exception
152    */

153   protected void setKeyPropertyParameter(SqlStatement stmt) throws ObjectNotDefinedException, PropertyFormatException,
154       DjenericException
155   {
156     try
157     {
158       DjProperty col = getExtent().getIdProperty();
159       stmt.setLong(col.getName(), getLong(col.getName()));
160     }
161     catch (SQLException JavaDoc x)
162     {
163       throw new DjenericException(x);
164     }
165   }
166
167   /**
168    * Copies the value of a resultset into an object. To find the values in the
169    * resultset the name of the property or the name of the mapping is used.
170    * Which type of identifier is used depends on parameter useNameNotMapping.
171    * If useNameNotMapping is true then the property name is used, else the
172    * mapping is used.
173    *
174    *@param rs The resultset to be used as source
175    *@param useNameNotMapping If useNameNotMapping is true then the property name is used
176    *@exception DjenericException Description of the Exception
177    */

178   protected void setFromRecord(ResultSet JavaDoc rs, boolean useNameNotMapping) throws DjenericException
179   {
180     try
181     {
182       setIgnoreModifications(true);
183       setBeingLoaded(true);
184
185       for (int i = 0; i < getExtent().getPropertyCount(); i++)
186       {
187         DjProperty col = getExtent().getProperty(i);
188         String JavaDoc propId;
189
190         if (useNameNotMapping) propId = col.getName();
191         else propId = col.getMapping();
192
193         int tp = col.getTypeCode();
194
195         if (tp == DjDomain.STRING_TYPE)
196         {
197           if (col.isMappedToLong())
198           {
199             byte[] bytes = SqlStatement.getBlob(rs, propId);
200             String JavaDoc value = null;
201             if (bytes != null) value = new String JavaDoc(bytes);
202             setString(i, value);
203           }
204           else
205           {
206             setString(i, rs.getString(propId));
207           }
208         }
209         else if (tp == DjDomain.INT_TYPE) setInt(i, rs.getInt(propId));
210         else if (tp == DjDomain.LONG_TYPE) setLong(i, rs.getLong(propId));
211         else if (tp == DjDomain.DATE_TYPE) setDate(i, rs.getTimestamp(propId));
212         else if (tp == DjDomain.BIGDECIMAL_TYPE) setBigDecimal(i, rs.getBigDecimal(propId));
213         else if (tp == DjDomain.BYTE_TYPE) setBytes(i, SqlStatement.getBlob(rs, propId));
214         else
215         {
216           // must be a Po then.. try setLong()
217
setLong(i, rs.getLong(propId));
218         }
219         if (rs.wasNull()) setNull(i);
220         // getInt(null) results to 0; fix this
221
}
222       setPersisted(true);
223       setModified(false);
224       updateOriginalPropertyValues();
225       getSession().cacheObject(this);
226
227       // Make sure to mark loading done; else validate will ignore the call
228
setBeingLoaded(false);
229       if (getSession().shouldValidateObjectsAfterLoading()) validate();
230
231       if (shouldTrace(DjPersistenceManager.TRACE_FLOW)) trace("Loaded " + getExtent().getObjectType() + " (id="
232                                                               + getObjectId() + ") " + toString());
233     }
234     catch (SQLException JavaDoc x)
235     {
236       throw new DjenericException(x);
237     }
238     catch (IOException JavaDoc x)
239     {
240       throw new DjenericException(x);
241     }
242     finally
243     {
244       setBeingLoaded(false);
245       setIgnoreModifications(false);
246     }
247   }
248
249   /**
250    * Description of the Method
251    *
252    *@exception DjenericException Description of the Exception
253    */

254   protected void update() throws DjenericException
255   {
256     checkRequiredProperties();
257     try
258     {
259       RdbmsExtent extent = (RdbmsExtent) getExtent();
260       SqlStatement stmt = extent.getUpdateStatement(getRdbmsSession(), getExtent().getPropertyNames(),
261                                                     getOriginalPropertyValues());
262       String JavaDoc keyProperty = extent.getIdProperty().getName();
263       for (int i = 0; i < extent.getPropertyCount(); i++)
264       {
265         DjProperty col = extent.getProperty(i);
266         if (col.getName().equals(keyProperty)) continue;
267         // The key column is not updated; not present in the stmt
268

269         boolean isNullValue = isNull(i);
270         int tp = col.getTypeCode();
271
272         if (tp == DjDomain.STRING_TYPE)
273         {
274           if (col.isMappedToLong())
275           {
276             if (isNullValue) stmt.setNull(col.getName(), Types.BLOB);
277             else stmt.setBlob(col.getName(), getBytes(i));
278           }
279           else
280           {
281             if (isNullValue) stmt.setNull(col.getName(), Types.VARCHAR);
282             else stmt.setString(col.getName(), getString(i));
283           }
284         }
285         else if (tp == DjDomain.INT_TYPE)
286         {
287           if (isNullValue) stmt.setNull(col.getName(), Types.INTEGER);
288           else stmt.setInt(col.getName(), getInt(i));
289         }
290         else if (tp == DjDomain.LONG_TYPE)
291         {
292           if (isNullValue) stmt.setNull(col.getName(), Types.BIGINT);
293           else stmt.setLong(col.getName(), getLong(i));
294         }
295         else if (tp == DjDomain.DATE_TYPE)
296         {
297           if (isNullValue) stmt.setNull(col.getName(), Types.TIMESTAMP);
298           else
299           {
300             // Be careful not to loose milli's:
301
if (getDate(i) instanceof java.sql.Timestamp JavaDoc) stmt.setTimestamp(col.getName(),
302                                                                             (java.sql.Timestamp JavaDoc) getDate(i));
303             else stmt.setTimestamp(col.getName(), new java.sql.Timestamp JavaDoc(getDate(i).getTime()));
304           }
305         }
306         else if (tp == DjDomain.BIGDECIMAL_TYPE)
307         {
308           if (isNullValue) stmt.setNull(col.getName(), Types.NUMERIC);
309           else stmt.setBigDecimal(col.getName(), getBigDecimal(i));
310         }
311         else if (tp == DjDomain.BYTE_TYPE)
312         {
313           if (isNullValue) stmt.setNull(col.getName(), Types.BINARY);
314           else stmt.setBlob(col.getName(), getBytes(i));
315         }
316         else throw new PersistenceException(Messages.getString("RdbmsDjenericObject.UnknownColumnType", col
317             .getTypeName()), this);
318       }
319       setOriginalWhereParameters(stmt);
320       int result = stmt.executeUpdate();
321       if (result == 0) throw new PersistenceException(Messages.getString("RdbmsDjenericObject.OutOfSynch", getExtent()
322           .getNameSingular()), this);
323       if (result > 1) throw new PersistenceException(Messages.getString("RdbmsDjenericObject.ReposCorrupt", String
324           .valueOf(getObjectId())), this);
325
326       if (shouldTrace(DjPersistenceManager.TRACE_FLOW)) trace("Updated " + getExtent().getObjectType() + " (id="
327                                                               + getObjectId() + ") " + toString());
328     }
329     catch (SQLException JavaDoc x)
330     {
331       throw new DjenericException(x);
332     }
333   }
334
335   /**
336    * Description of the Method
337    *
338    *@exception DjenericException Description of the Exception
339    */

340   protected void insert() throws DjenericException
341   {
342     checkRequiredProperties();
343     try
344     {
345       RdbmsExtent extent = (RdbmsExtent) getExtent();
346       SqlStatement stmt = extent.getInsertStatement(getRdbmsSession());
347
348       String JavaDoc keyCol = getIdPropertyName();
349       if (isNull(keyCol))
350       {
351         setLong(keyCol, getRdbmsSession().getPersistenceManager().getNextObjectId());
352       }
353
354       for (int i = 0; i < extent.getPropertyCount(); i++)
355       {
356         DjProperty col = extent.getProperty(i);
357         int tp = col.getTypeCode();
358
359         boolean isNullValue = isNull(i);
360
361         if (tp == DjDomain.STRING_TYPE)
362         {
363           if (col.isMappedToLong())
364           {
365             if (isNullValue) stmt.setNull(col.getName(), Types.BLOB);
366             else stmt.setBlob(col.getName(), getBytes(i));
367           }
368           else
369           {
370             if (isNullValue) stmt.setNull(col.getName(), Types.VARCHAR);
371             else stmt.setString(col.getName(), getString(i));
372           }
373         }
374         else if (tp == DjDomain.INT_TYPE)
375         {
376           if (isNullValue) stmt.setNull(col.getName(), Types.INTEGER);
377           else stmt.setInt(col.getName(), getInt(i));
378         }
379         else if (tp == DjDomain.LONG_TYPE)
380         {
381           if (isNullValue) stmt.setNull(col.getName(), Types.BIGINT);
382           else stmt.setLong(col.getName(), getLong(i));
383         }
384         else if (tp == DjDomain.DATE_TYPE)
385         {
386           if (isNullValue) stmt.setNull(col.getName(), Types.DATE);
387           else stmt.setTimestamp(col.getName(), new java.sql.Timestamp JavaDoc(getDate(i).getTime()));
388         }
389         else if (tp == DjDomain.BIGDECIMAL_TYPE)
390         {
391           if (isNullValue) stmt.setNull(col.getName(), Types.NUMERIC);
392           else stmt.setBigDecimal(col.getName(), getBigDecimal(i));
393         }
394         else if (tp == DjDomain.BYTE_TYPE)
395         {
396           if (isNullValue) stmt.setNull(col.getName(), Types.BINARY);
397           else stmt.setBlob(col.getName(), getBytes(i));
398         }
399         else throw new PersistenceException(Messages.getString("RdbmsDjenericObject.UnknownColumnType", col
400             .getTypeName()), this);
401       }
402       stmt.executeUpdate();
403
404       if (shouldTrace(DjPersistenceManager.TRACE_FLOW)) trace("Inserted " + getExtent().getObjectType() + " (id="
405                                                               + getObjectId() + ") " + toString());
406     }
407     catch (SQLException JavaDoc x)
408     {
409       throw new DjenericException(x);
410     }
411   }
412
413   /**
414    * Description of the Method
415    *
416    *@exception DjenericException Description of the Exception
417    */

418   protected void delete() throws DjenericException
419   {
420     try
421     {
422       RdbmsExtent extent = (RdbmsExtent) getExtent();
423       SqlStatement stmt = extent.getDeleteStatement(getRdbmsSession(), getExtent().getPropertyNames(),
424                                                     getOriginalPropertyValues());
425       setOriginalWhereParameters(stmt);
426       int result = stmt.executeUpdate();
427
428       if (result == 0)
429       {
430         // No record hit?!
431
boolean shouldThrow = false;
432         try
433         {
434           reload();
435           // If this succeeds the record was updated by another user!
436
shouldThrow = true;
437           // WOOPS!
438
}
439         catch (NotPersistedException x)
440         {
441           // ignore this then; somebody else deleted it for us; that's ok too...
442
}
443         if (shouldThrow)
444         {
445           throw new CanNotDeleteException(Messages.getString("RdbmsDjenericObject.DeleteFailed", getExtent()
446               .getNameSingular()), this, null);
447         }
448       }
449       if (result > 1) throw new PersistenceException(Messages.getString("RdbmsDjenericObject.ReposCorrupt", String
450           .valueOf(getObjectId())), this);
451
452       if (shouldTrace(DjPersistenceManager.TRACE_FLOW)) trace("Deleted " + getExtent().getObjectType() + " (id="
453                                                               + getObjectId() + ") " + toString());
454     }
455     catch (SQLException JavaDoc x)
456     {
457       throw new DjenericException(x);
458     }
459   }
460
461   /**
462    * Description of the Method
463    *
464    *@exception DjenericException Description of the Exception
465    */

466   public void reload() throws DjenericException
467   {
468     if (isTransient()) return;
469
470     try
471     {
472       RdbmsExtent extent = (RdbmsExtent) getExtent();
473       SqlStatement stmt = extent.getSelectStatement(getRdbmsSession());
474       setKeyPropertyParameter(stmt);
475       ResultSet JavaDoc rs = null;
476       try
477       {
478         rs = stmt.executeQuery();
479         if (!rs.next()) throw new NotPersistedException(Messages.getString("RdbmsDjenericObject.CouldNotReload",
480                                                                            getExtent().getNameSingular(),
481                                                                            getDescriptor()), this);
482         setFromRecord(rs, true);
483
484         if (shouldTrace(DjPersistenceManager.TRACE_FLOW)) trace("Reloaded " + getExtent().getObjectType() + " (id="
485                                                                 + getObjectId() + ") " + toString());
486       }
487       finally
488       {
489         if (rs != null) rs.close();
490         stmt.close();
491       }
492     }
493     catch (SQLException JavaDoc x)
494     {
495       throw new DjenericException(x);
496     }
497   }
498 }
Popular Tags