KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > broker > util > sequence > SequenceManagerMySQLImpl


1 package org.apache.ojb.broker.util.sequence;
2 /* Copyright 2002-2004 The Apache Software Foundation
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 import java.math.BigDecimal JavaDoc;
17 import java.sql.Date JavaDoc;
18 import java.sql.SQLException JavaDoc;
19 import java.sql.Time JavaDoc;
20 import java.sql.Timestamp JavaDoc;
21 import java.sql.Types JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Vector JavaDoc;
24
25 import org.apache.ojb.broker.PersistenceBroker;
26 import org.apache.ojb.broker.PersistenceBrokerException;
27 import org.apache.ojb.broker.accesslayer.JdbcAccess;
28 import org.apache.ojb.broker.accesslayer.ResultSetAndStatement;
29 import org.apache.ojb.broker.core.proxy.ProxyHelper;
30 import org.apache.ojb.broker.metadata.ClassDescriptor;
31 import org.apache.ojb.broker.metadata.FieldDescriptor;
32 import org.apache.ojb.broker.metadata.ObjectReferenceDescriptor;
33 import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
34 import org.apache.ojb.broker.query.Query;
35 import org.apache.ojb.broker.util.logging.Logger;
36 import org.apache.ojb.broker.util.logging.LoggerFactory;
37
38 /**
39  * MySQL SequenceManager for use with auto_increment columns.
40  * <p>
41  * <b>WARNING:</b> Not thoroughly tested, use at own risk. ;-)
42  * <br/>
43  * Native key generation is not extent aware if the extent persistent
44  * objects using different database tables.
45  *
46  * <p>
47  * Implementation configuration properties:
48  * </p>
49  *
50  * <table cellspacing="2" cellpadding="2" border="3" frame="box">
51  * <tr>
52  * <td><strong>Property Key</strong></td>
53  * <td><strong>Property Values</strong></td>
54  * </tr>
55  * <tr>
56  * <td>none</td>
57  * <td>
58  *
59  * </td>
60  * </tr>
61  * </table>
62  * <br/>
63  * <br/>
64  *
65  * @deprecated this SequenceManager implementation is outdated and will be removed,
66  * use {@link SequenceManagerNativeImpl} instead
67  *
68  * @author Travis Reeder - travis@spaceprogram.com
69  * @version $Id: SequenceManagerMySQLImpl.java,v 1.21 2004/05/22 11:24:51 brj Exp $
70  *
71  */

72 public class SequenceManagerMySQLImpl implements SequenceManager
73 {
74     private Logger log = LoggerFactory.getLogger(SequenceManagerMySQLImpl.class);
75
76     /**
77      * reference to the PersistenceBroker
78      */

79     protected PersistenceBroker broker;
80
81     public SequenceManagerMySQLImpl(PersistenceBroker broker)
82     {
83         this.broker = broker;
84     }
85
86     /**
87      * Returns next Id get from "sequence sequence.NextVal from Dual".
88      * Mount sequence name as:
89      * Schema.SQ_tableName_fieldName. If you have a table named MY_TABLE
90      * and the sequenced field is MY_FIELD on schema MY_SCHEMA, the command
91      * to create the sequence is:
92      * CREATE SEQUENCE MY_SCHEMA.SQ_MY_TABLE_MY_FIELD
93      */

94     private synchronized int getNextId(FieldDescriptor field)
95     {
96         return 0;
97     }
98
99     /**
100      * returns a unique int for class clazz and field fieldName.
101      * the returned uid is unique accross all tables in the extent of clazz.
102      */

103     public int getUniqueId(FieldDescriptor field)
104     {
105         return getNextId(field);
106     }
107
108     /**
109      * returns a unique String for class clazz and field fieldName.
110      * the returned uid is unique accross all tables in the extent of clazz.
111      *
112      */

113     protected String JavaDoc getUniqueString(FieldDescriptor field)
114     {
115         return Integer.toString(getUniqueId(field));
116     }
117
118     /**
119      * returns a unique long value for class clazz and field fieldName.
120      * the returned number is unique accross all tables in the extent of clazz.
121      */

122     protected long getUniqueLong(FieldDescriptor field)
123     {
124         return getUniqueId(field);
125     }
126
127     /**
128      * returns a unique Object for class clazz and field fieldName.
129      * the returned Object is unique accross all tables in the extent of clazz.
130      */

131     protected Object JavaDoc getUniqueObject(FieldDescriptor field)
132     {
133         return null; //getUniqueString(clazz, fieldName);
134
}
135
136     public void afterStore(JdbcAccess dbAccess, ClassDescriptor cld, Object JavaDoc obj) throws SequenceManagerException
137     {
138         FieldDescriptor[] fldArr = cld.getAutoIncrementFields();
139         FieldDescriptor fd = fldArr.length > 0 ? fldArr[0] : null;
140         if(fd != null)
141         { // an autoinc column exists
142
ResultSetAndStatement rsStmt = null;
143             try
144             {
145                 rsStmt = dbAccess.executeSQL("SELECT LAST_INSERT_ID() as newid FROM " + cld.getFullTableName(), cld, Query.NOT_SCROLLABLE);
146                 int newid = 0;
147                 if (rsStmt.m_rs.next())
148                 {
149                     newid = rsStmt.m_rs.getInt("newid");
150                 }
151                 rsStmt.m_rs.close();
152                 if(log.isDebugEnabled()) log.debug("After store - newid=" + newid);
153
154                 PersistentField pf = fd.getPersistentField();
155                 pf.set(obj, new Integer JavaDoc(newid));
156             }
157             catch (PersistenceBrokerException e)
158             {
159                 throw new SequenceManagerException(e);
160             }
161             catch (SQLException JavaDoc e)
162             {
163                 throw new SequenceManagerException(e);
164             }
165             finally
166             {
167                 rsStmt.close();
168             }
169         }
170
171     }
172
173     public void setReferenceFKs(Object JavaDoc obj, ClassDescriptor cld) throws SequenceManagerException
174     {
175
176         Vector JavaDoc objectReferenceDescriptors = cld.getObjectReferenceDescriptors();
177         // get all members of obj that are references and assign FKs
178
Iterator JavaDoc i = objectReferenceDescriptors.iterator();
179         while (i.hasNext())
180         {
181             ObjectReferenceDescriptor rds =
182                     (ObjectReferenceDescriptor) i.next();
183             Object JavaDoc ref = rds.getPersistentField().get(obj);
184             if(ref != null){ // make sure the ref object actually exists
185
assertFkAssignment(obj, cld, ref, rds);
186             }
187         }
188     }
189
190     /**
191      *
192      * @param obj
193      * @param cld
194      * @param ref the object that is the reference descriptor
195      * @param rds
196      */

197     private void assertFkAssignment(Object JavaDoc obj, ClassDescriptor cld, Object JavaDoc ref, ObjectReferenceDescriptor rds)
198     {
199         // avoid problems with proxy instances
200
Class JavaDoc c = ProxyHelper.getRealClass(ref);
201
202         // get ClassDescriptor for RefDescriptor object
203
ClassDescriptor refCld =
204                 broker.getDescriptorRepository().getDescriptorFor(c);
205         ClassDescriptor objCld = cld;
206
207         // get all the fielddescriptors in the objects that reference this one so we can set the new id
208
FieldDescriptor[] objFkFields =
209                 rds.getForeignKeyFieldDescriptors(objCld);
210         if (objFkFields != null)
211         {
212             FieldDescriptor refFld = refCld.getAutoIncrementFields()[0];
213             FieldDescriptor fld = null;
214             for (int i = 0; i < objFkFields.length; i++)
215             {
216                 fld = objFkFields[i];
217                 fld.getPersistentField().set(obj, refFld.getPersistentField().get(ref));
218             }
219         }
220     }
221
222     /**
223      * Returns a unique object for the given field attribute.
224      * The returned value takes in account the jdbc-type
225      * and the FieldConversion.sql2java() conversion defined for <code>field</code>.
226      * The returned object is unique accross all tables in the extent
227      * of class the field belongs to.
228      */

229     public Object JavaDoc getUniqueValue(FieldDescriptor field) throws SequenceManagerException
230     {
231         Object JavaDoc result = null;
232         switch (field.getJdbcType().getType())
233         {
234             case Types.ARRAY:
235             {
236                 Object JavaDoc[] arr = {getUniqueString(field)};
237                 result = arr;
238                 break;
239             }
240             case Types.BIGINT:
241             {
242                 result = new Long JavaDoc(getUniqueLong(field));
243                 break;
244             }
245             case Types.BINARY:
246             {
247                 result = getUniqueString(field).getBytes();
248                 break;
249             }
250             case Types.CHAR:
251             {
252                 result = getUniqueString(field);
253                 break;
254             }
255             case Types.DATE:
256             {
257                 result = new Date JavaDoc(getUniqueLong(field));
258                 break;
259             }
260             case Types.DECIMAL:
261             {
262                 result = new BigDecimal JavaDoc(getUniqueLong(field));
263                 break;
264             }
265             case Types.DOUBLE:
266             {
267                 result = new Double JavaDoc(getUniqueLong(field));
268                 break;
269             }
270             case Types.FLOAT:
271             {
272                 result = new Double JavaDoc(getUniqueLong(field));
273                 break;
274             }
275             case Types.INTEGER:
276             {
277                 result = new Integer JavaDoc(getUniqueId(field));
278                 break;
279             }
280             case Types.JAVA_OBJECT:
281             {
282                 result = getUniqueObject(field);
283                 break;
284             }
285             case Types.LONGVARBINARY:
286             {
287                 result = getUniqueString(field).getBytes();
288                 break;
289             }
290             case Types.LONGVARCHAR:
291             {
292                 result = getUniqueString(field);
293                 break;
294             }
295             case Types.NUMERIC:
296             {
297                 result = new BigDecimal JavaDoc(getUniqueLong(field));
298                 break;
299             }
300             case Types.REAL:
301             {
302                 result = new Float JavaDoc(getUniqueLong(field));
303                 break;
304             }
305             case Types.SMALLINT:
306             {
307                 result = new Short JavaDoc((short)getUniqueId(field));
308                 break;
309             }
310             case Types.TIME:
311             {
312                 result = new Time JavaDoc(getUniqueLong(field));
313                 break;
314             }
315             case Types.TIMESTAMP:
316             {
317                 result = new Timestamp JavaDoc(getUniqueLong(field));
318                 break;
319             }
320             case Types.TINYINT:
321             {
322                 result = new Byte JavaDoc((byte)getUniqueId(field));
323                 break;
324             }
325             case Types.VARBINARY:
326             {
327                 result = getUniqueString(field).getBytes();
328                 break;
329             }
330             case Types.VARCHAR:
331             {
332                 result = getUniqueString(field);
333                 break;
334             }
335             default:
336             {
337                 result = getUniqueString(field);
338                 break;
339             }
340         }
341         result = field.getFieldConversion().sqlToJava(result);
342         return result;
343     }
344 }
345
Popular Tags