KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > broker > PerformanceJdbcReferenceTest


1 package org.apache.ojb.broker;
2
3 import junit.framework.TestCase;
4 import org.apache.ojb.broker.accesslayer.ConnectionFactory;
5 import org.apache.ojb.broker.accesslayer.ConnectionFactoryFactory;
6 import org.apache.ojb.broker.metadata.ClassDescriptor;
7 import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
8 import org.apache.ojb.broker.metadata.MetadataManager;
9 import org.apache.ojb.broker.query.Criteria;
10 import org.apache.ojb.broker.query.Query;
11 import org.apache.ojb.broker.query.QueryByCriteria;
12 import org.apache.ojb.broker.util.logging.Logger;
13 import org.apache.ojb.broker.util.logging.LoggerFactory;
14
15 import java.sql.Connection JavaDoc;
16 import java.sql.PreparedStatement JavaDoc;
17 import java.sql.ResultSet JavaDoc;
18
19 /**
20  * This TestCase contains the OJB performance benchmarks for the
21  * JDBC API.
22  * This is the reference for other benchmarks.
23  * @author Thomas Mahler
24  */

25 public class PerformanceJdbcReferenceTest extends TestCase
26 {
27     private Logger logger = LoggerFactory.getLogger("performance");;
28
29     /**
30      * the number of PerformanceArticle objects to work with.
31      */

32     static int articleCount = 10000;
33
34     /**
35      * the number of iterations to perform.
36      */

37     static int iterations = 2;
38
39     /**
40      * the offset value for PerformanceArticle primary keys
41      */

42     int offsetId = 10000;
43     PersistenceBroker broker;
44     private PerformanceArticle[] arr;
45
46     /**
47      * BrokerTests constructor comment.
48      * @param name java.lang.String
49      */

50     public PerformanceJdbcReferenceTest(String JavaDoc name)
51
52     {
53         super(name);
54     }
55
56     /**
57      * launches the TestCase.
58      * The number of Objects to work with and the number of iterations
59      * to be performed can be adjusted by setting them as commandline parameters.
60      * @param args the String[] holding the commandline parameters.
61      */

62     public static void main(String JavaDoc[] args)
63     {
64         if (args.length > 0)
65         {
66             articleCount = Integer.parseInt(args[0]);
67         }
68         if (args.length > 1)
69         {
70             iterations = Integer.parseInt(args[1]);
71         }
72
73         String JavaDoc[] arr = {PerformanceJdbcReferenceTest.class.getName()};
74         junit.textui.TestRunner.main(arr);
75     }
76
77     /**
78      * setting up the test fixture.
79      */

80     public void setUp() throws Exception JavaDoc
81     {
82         broker = PersistenceBrokerFactory.defaultPersistenceBroker();
83
84         arr = new PerformanceArticle[articleCount];
85         for (int i = 0; i < articleCount; i++)
86         {
87             PerformanceArticle a = createArticle(offsetId + i);
88             arr[i] = a;
89         }
90     }
91
92     /**
93      * tearing down the test fixture.
94      */

95     public void tearDown()
96     {
97         broker.close();
98     }
99
100     /**
101      * factory method that createa an PerformanceArticle with a given id.
102      * @return the created PerformanceArticle object
103      * @param id the primary key value for the new object
104      */

105     private PerformanceArticle createArticle(int id)
106     {
107         PerformanceArticle a = new PerformanceArticle();
108         a.setArticleId(id);
109         a.setArticleName("New Performance Article " + id);
110         a.setMinimumStock(100);
111         a.setOrderedUnits(17);
112         a.setPrice(100.0);
113         a.setProductGroupId(1);
114         a.setStock(234);
115         a.setSupplierId(4);
116         a.setUnit("bottle");
117         return a;
118     }
119
120     /**
121      * obtain a JDBC Connection. OJB API is used to make this code portable for
122      * other target dabases and different lookup methods.
123      * @return the Connection to be used
124      */

125     private Connection JavaDoc getConnection() throws Exception JavaDoc
126     {
127         // Use OJB API to obtain JDBC Connection. All settings are read from
128
// the repository.xml file.
129
ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
130         JdbcConnectionDescriptor jcd = MetadataManager.getInstance().connectionRepository()
131                 .getDescriptor(TestHelper.DEF_KEY);
132         ConnectionFactory cf = ConnectionFactoryFactory.getInstance().createConnectionFactory();
133         Connection JavaDoc conn = cf.lookupConnection(jcd);
134         return conn;
135     }
136
137      private void returnConnection(Connection JavaDoc conn) throws Exception JavaDoc
138     {
139         // Use OJB API to obtain JDBC Connection. All settings are read from
140
// the repository.xml file.
141
ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
142         JdbcConnectionDescriptor jcd = MetadataManager.getInstance().connectionRepository()
143                 .getDescriptor(TestHelper.DEF_KEY);
144         ConnectionFactory cf = ConnectionFactoryFactory.getInstance().createConnectionFactory();
145         cf.releaseConnection(jcd, conn);
146     }
147
148     /**
149      * deletes all PerformanceArticle created by <code>insertNewArticles</code>.
150      */

151     protected void deleteArticles() throws Exception JavaDoc
152     {
153         Connection JavaDoc conn = getConnection();
154
155         // Use the OJB SqlGenerator to generate SQL Statements. All details about
156
// Table and column names are read from the repository.xml file.
157
ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
158         String JavaDoc sql = broker.serviceSqlGenerator().getPreparedDeleteStatement(cld);
159
160         logger.debug("delete stmt: " + sql);
161
162         long start = System.currentTimeMillis();
163         try
164         {
165             conn.setAutoCommit(false);
166             PreparedStatement JavaDoc stmt = conn.prepareStatement(sql);
167             for (int i = 0; i < articleCount; i++)
168             {
169                 PerformanceArticle a = arr[i];
170                 stmt.setInt(1, a.articleId);
171                 stmt.execute();
172             }
173             conn.commit();
174         }
175         catch (Throwable JavaDoc t)
176         {
177             logger.error(t);
178             fail(t.getMessage());
179         }
180         finally
181         {
182             if (conn != null)
183                 returnConnection(conn);
184         }
185         long stop = System.currentTimeMillis();
186         logger.info("deleting " + articleCount + " Objects: " + (stop - start) + " msec");
187     }
188
189     /**
190      * create new PerformanceArticle objects and insert them into the RDBMS.
191      * The number of objects to create is defined by <code>articleCount</code>.
192      */

193     protected void insertNewArticles() throws Exception JavaDoc
194     {
195         clearTable();
196
197         Connection JavaDoc conn = getConnection();
198
199         // Use the OJB SqlGenerator to generate SQL Statements. All details about
200
// Table and column names are read from the repository.xml file.
201
ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
202         String JavaDoc sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld);
203
204         logger.debug("insert stmt: " + sql);
205
206         long start = System.currentTimeMillis();
207         try
208         {
209             conn.setAutoCommit(false);
210             PreparedStatement JavaDoc stmt = conn.prepareStatement(sql);
211
212             for (int i = 0; i < articleCount; i++)
213             {
214                 PerformanceArticle a = arr[i];
215
216                 stmt.setInt(1, a.articleId);
217                 stmt.setString(2, a.articleName);
218                 stmt.setInt(3, a.supplierId);
219                 stmt.setInt(4, a.productGroupId);
220                 stmt.setString(5, a.unit);
221                 stmt.setDouble(6, a.price);
222                 stmt.setInt(7, a.stock);
223                 stmt.setInt(8, a.orderedUnits);
224                 stmt.setInt(9, a.minimumStock);
225
226                 stmt.execute();
227             }
228             conn.commit();
229         }
230         catch (Throwable JavaDoc t)
231         {
232             logger.error(t);
233             fail(t.getMessage());
234         }
235         finally
236         {
237             if (conn != null)
238                 returnConnection(conn);
239         }
240         long stop = System.currentTimeMillis();
241         logger.info("inserting " + articleCount + " Objects: " + (stop - start) + " msec");
242
243     }
244
245     protected void clearTable() throws Exception JavaDoc
246     {
247         Connection JavaDoc conn = getConnection();
248         ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
249         String JavaDoc table = cld.getFullTableName();
250         String JavaDoc column = cld.getFieldDescriptorByName("articleId").getColumnName();
251         String JavaDoc sql = "DELETE FROM " + table + " WHERE " + column + " >= " + offsetId;
252         PreparedStatement JavaDoc stmt = conn.prepareStatement(sql);
253         stmt.execute();
254         returnConnection(conn);
255     }
256
257     /**
258      * read in all the PerformanceArticles from the RDBMS that have
259      * been inserted by <code>insertNewArticles()</code>.
260      * The lookup is done one by one, that is: a primary key based lookup is used.
261      */

262     protected void readArticles() throws Exception JavaDoc
263     {
264         Connection JavaDoc conn = getConnection();
265
266         // Use the OJB SqlGenerator to generate SQL Statements. All details about
267
// Table and column names are read from the repository.xml file.
268
ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
269         String JavaDoc sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);
270         logger.debug("select stmt: " + sql);
271
272         String JavaDoc colId = cld.getFieldDescriptorByName("articleId").getColumnName();
273         String JavaDoc colName = cld.getFieldDescriptorByName("articleName").getColumnName();
274         String JavaDoc colSupplier = cld.getFieldDescriptorByName("supplierId").getColumnName();
275         String JavaDoc colGroup = cld.getFieldDescriptorByName("productGroupId").getColumnName();
276         String JavaDoc colUnit = cld.getFieldDescriptorByName("unit").getColumnName();
277         String JavaDoc colPrice = cld.getFieldDescriptorByName("price").getColumnName();
278         String JavaDoc colStock = cld.getFieldDescriptorByName("stock").getColumnName();
279         String JavaDoc colOrdered = cld.getFieldDescriptorByName("orderedUnits").getColumnName();
280         String JavaDoc colMin = cld.getFieldDescriptorByName("minimumStock").getColumnName();
281
282         long start = System.currentTimeMillis();
283         try
284         {
285             conn.setAutoCommit(false);
286             PreparedStatement JavaDoc stmt = conn.prepareStatement(sql);
287             for (int i = 0; i < articleCount; i++)
288             {
289                 stmt.setInt(1, offsetId + i);
290                 ResultSet JavaDoc rs = stmt.executeQuery();
291                 rs.next();
292
293                 PerformanceArticle a = new PerformanceArticle();
294                 a.articleId = rs.getInt(colId);
295                 a.articleName = rs.getString(colName);
296                 a.supplierId = rs.getInt(colSupplier);
297                 a.productGroupId = rs.getInt(colGroup);
298                 a.unit = rs.getString(colUnit);
299                 a.price = rs.getFloat(colPrice);
300                 a.stock = rs.getInt(colStock);
301                 a.orderedUnits = rs.getInt(colOrdered);
302                 a.minimumStock = rs.getInt(colMin);
303             }
304         }
305         catch (Throwable JavaDoc t)
306         {
307             logger.error(t);
308             fail(t.getMessage());
309         }
310         finally
311         {
312             if (conn != null)
313                 returnConnection(conn);
314         }
315
316         long stop = System.currentTimeMillis();
317         logger.info("querying " + articleCount + " Objects: " + (stop - start) + " msec");
318
319     }
320
321     /**
322      * read in all the PerformanceArticles from the RDBMS that have
323      * been inserted by <code>insertNewArticles()</code>.
324      * The lookup is done with a cursor fetch,
325      * that is: a between Statement is used to select all inserted PerformanceArticles
326      * and Objects are read in by fetching from the cursor (JDBC ResultSet).
327      */

328     protected void readArticlesByCursor() throws Exception JavaDoc
329     {
330         Connection JavaDoc conn = getConnection();
331
332         Criteria c = new Criteria();
333         c.addBetween("articleId", new Integer JavaDoc(offsetId), new Integer JavaDoc(offsetId + articleCount));
334         Query query = new QueryByCriteria(PerformanceArticle.class, c);
335
336         // Use the OJB SqlGenerator to generate SQL Statements. All details about
337
// Table and column names are read from the repository.xml file.
338
ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
339         String JavaDoc sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);
340
341         logger.debug("select stmt: " + sql);
342
343         String JavaDoc colId = cld.getFieldDescriptorByName("articleId").getColumnName();
344         String JavaDoc colName = cld.getFieldDescriptorByName("articleName").getColumnName();
345         String JavaDoc colSupplier = cld.getFieldDescriptorByName("supplierId").getColumnName();
346         String JavaDoc colGroup = cld.getFieldDescriptorByName("productGroupId").getColumnName();
347         String JavaDoc colUnit = cld.getFieldDescriptorByName("unit").getColumnName();
348         String JavaDoc colPrice = cld.getFieldDescriptorByName("price").getColumnName();
349         String JavaDoc colStock = cld.getFieldDescriptorByName("stock").getColumnName();
350         String JavaDoc colOrdered = cld.getFieldDescriptorByName("orderedUnits").getColumnName();
351         String JavaDoc colMin = cld.getFieldDescriptorByName("minimumStock").getColumnName();
352
353
354         int fetchCount = 0;
355         long start = System.currentTimeMillis();
356         try
357         {
358             conn.setAutoCommit(false);
359             PreparedStatement JavaDoc stmt = conn.prepareStatement(sql);
360             stmt.setInt(1, offsetId);
361             stmt.setInt(2, offsetId + articleCount);
362             ResultSet JavaDoc rs = stmt.executeQuery();
363             while (rs.next())
364             {
365                 fetchCount++;
366
367                 PerformanceArticle a = new PerformanceArticle();
368                 a.articleId = rs.getInt(colId);
369                 a.articleName = rs.getString(colName);
370                 a.supplierId = rs.getInt(colSupplier);
371                 a.productGroupId = rs.getInt(colGroup);
372                 a.unit = rs.getString(colUnit);
373                 a.price = rs.getFloat(colPrice);
374                 a.stock = rs.getInt(colStock);
375                 a.orderedUnits = rs.getInt(colOrdered);
376                 a.minimumStock = rs.getInt(colMin);
377             }
378         }
379         catch (Throwable JavaDoc t)
380         {
381             logger.error(t);
382             fail(t.getMessage());
383         }
384         finally
385         {
386             if (conn != null)
387                 returnConnection(conn);
388         }
389
390         long stop = System.currentTimeMillis();
391         logger.info("fetching " + fetchCount + " Objects: " + (stop - start) + " msec");
392
393     }
394
395     /**
396      * updates all PerformanceArticles inserted by <code>insertNewArticles()</code>.
397      * All objects are modified and changes are written to the RDBMS with an UPDATE.
398      */

399     protected void updateExistingArticles() throws Exception JavaDoc
400     {
401         Connection JavaDoc conn = getConnection();
402
403         // Use the OJB SqlGenerator to generate SQL Statements. All details about
404
// Table and column names are read from the repository.xml file.
405
ClassDescriptor cld = broker.getClassDescriptor(PerformanceArticle.class);
406         String JavaDoc sql = broker.serviceSqlGenerator().getPreparedUpdateStatement(cld);
407         logger.debug("update stmt: " + sql);
408
409         // update all objects
410
for (int i = 0; i < articleCount; i++)
411         {
412             arr[i].setPrice(arr[i].getPrice() * 1.95583);
413         }
414
415         long start = System.currentTimeMillis();
416         try
417         {
418             conn.setAutoCommit(false);
419             PreparedStatement JavaDoc stmt = conn.prepareStatement(sql);
420             for (int i = 0; i < articleCount; i++)
421             {
422                 PerformanceArticle a = arr[i];
423                 stmt.setString(1, a.articleName);
424                 stmt.setInt(2, a.supplierId);
425                 stmt.setInt(3, a.productGroupId);
426                 stmt.setString(4, a.unit);
427                 stmt.setDouble(5, a.price);
428                 stmt.setInt(6, a.stock);
429                 stmt.setInt(7, a.orderedUnits);
430                 stmt.setInt(8, a.minimumStock);
431                 stmt.setInt(9, a.articleId);
432                 stmt.execute();
433             }
434             conn.commit();
435         }
436         catch (Throwable JavaDoc t)
437         {
438             logger.error(t);
439             fail(t.getMessage());
440         }
441         finally
442         {
443             if (conn != null)
444                 returnConnection(conn);
445         }
446         long stop = System.currentTimeMillis();
447         logger.info("updating " + articleCount + " Objects: " + (stop - start) + " msec");
448
449     }
450
451     /**
452      * this method is the driver for the complete Benchmark.
453      * It performs the following steps:
454      *
455      * 1.) n objects are created and inserted to the RDBMS.
456      * 2.) the created objects are modified. Modifications are written to the RDBMS with updates.
457      * 3.) All objects created in 1.) are read in by primary key based SELECT statements.
458      * 4.) Step 3.) is repeated to test caching facilities.
459      * 5.) All objects created in 1.) are read by iterating over a ResultSet.
460      * 6.) All objects created in 1.) are deleted with n separate DELETE Statements.
461      */

462     public void testBenchmark()
463     {
464         try
465         {
466             logger.info("Test for native JDBC");
467             for (int i = 0; i < iterations; i++)
468             {
469                 logger.info("");
470
471                 // store all Article objects
472
insertNewArticles();
473
474                 // update all objects
475
updateExistingArticles();
476
477                 // querying
478
readArticles();
479
480                 readArticles();
481
482                 // fetching objects
483
readArticlesByCursor();
484
485                 // delete all objects
486
deleteArticles();
487             }
488         }
489         catch (Throwable JavaDoc t)
490         {
491             logger.error(t);
492             fail(t.getMessage());
493         }
494     }
495
496 }
497
Popular Tags