JDBC Best Practices for Oracle   Programmers       Derek C. Ashmore       Over 6 years of Java-related experience       Ov...
Data Access Options       JDBC       SQL/J       J2EE Entity Beans       Object-Relational Mapping Toolsets            Hib...
Why focus on JDBC?       JDBC the most commonly used.            Not a technical judgment – just an observation.       Why...
Why “JDBC Best Practices”?       If we’re going to use JDBC, we should use it       well.       It’s a complex tool with l...
Agenda       Best Practices            Practices applicable to all types of Java/JDBC code            used with Oracle dat...
Best Practices Summary       Close JDBC Objects in a “finally” block.       Turn off auto-commit for select activity      ...
Best Practices Summary   (con’t)       Reference java.sql or javax.sql classes       only            Avoid vendor-specific...
Best Practices Summary   (con’t)       Use Timestamp objects as host       variables instead of Strings for DATE       col...
Close all JDBC Objects       Close all JDBC Objects in a finally block            Stranded JDBC consume scarce db resource...
Closure Issues       Close() throws a SQLException                 Leads to nested try/catch logic in the finally         ...
Closure Issues (con’t)       Finding Stranded JDBC Objects       Problematic            Use P6Spy with an extension librar...
Turn off auto-commit for   select activity       Oracle does not issue locks on reads       unless you specify the “for up...
Audit use of Platform-specific   features       Only use when clear benefit – not out of habit       Creates a portability...
Specify Column Lists       Always specify column lists in select and       insert statements.            Code won’t break ...
Use Statement Batching       Groups updates, inserts, and deletes together       in groups            Has Fewer network ro...
Set the query fetch size       Instruct database to return rows in batches of       10 to 100.       Has Fewer network rou...
Reference java.sql or javax.sql   classes only       Avoid direct use of Oracle-specific class       implementations      ...
Utilize Connection Pooling       Connection Pools eliminate wait time for       database connections by creating them ahea...
Use RowId for faster updates   and deletes       RowId contains information about where a       row physically is         ...
Use Timestamp objects for   DATE columns       Oracle DATE columns contain “time”       Use Timestamp for selects and as h...
Consolidate SQL String   formation       Some developers dynamically build the SQL       string with scattered concatenati...
Consolidate SQL String (con’t)       Advantages                 Easier to read                 Saves String Processing    ...
Separate JDBC code from   business logic       Make it a separate package            com.jmu.myapp.data       Easier to sh...
Common Questions       When should I be using Stored       Procedures?            When should Java be inside the database ...
Stored Procedure Use       Aren’t Stored Procedures better performing?            Depends on platform                 Syba...
PreparedStatement Use       PreparedStatements are recommended for       most cases       Statements can be faster from th...
PreparedStatement Caching       Oracle has the ability to cache       PreparedStatements on the client side       This is ...
Latest Developments       JDBC 3.0 Specification            Standardizes Connection Pooling            Adds PreparedStatem...
Future Directions       JDBC is a maturing spec            Expect frequency of change to slow considerably       Use of Ob...
Questions       Derek C. Ashmore       Author of The J2EE™ Architect’s       Handbook            Downloadable at:         ...
Upcoming SlideShare
Loading in...5
×

Jdbc Best Practices - Oracle/IOUG, Toronto, April 21, 2004

200

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
200
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Jdbc Best Practices - Oracle/IOUG, Toronto, April 21, 2004"

  1. 1. JDBC Best Practices for Oracle Programmers Derek C. Ashmore Over 6 years of Java-related experience Over 10 years of database design/administration experience. Author of The J2EE™ Architect’s Handbook Downloadable at: http://www.dvtpress.com/javaarch Can be reached at dashmore@dvt.comApril 21, 2004 © 2004, Derek C. Ashmore
  2. 2. Data Access Options JDBC SQL/J J2EE Entity Beans Object-Relational Mapping Toolsets Hibernate JDO Many others…..April 21, 2004 © 2004, Derek C. Ashmore
  3. 3. Why focus on JDBC? JDBC the most commonly used. Not a technical judgment – just an observation. Why is JDBC the most common access method? It was the first access method available. It works It satisfies developers needs Most databases support it. Many Developers already know itApril 21, 2004 © 2004, Derek C. Ashmore
  4. 4. Why “JDBC Best Practices”? If we’re going to use JDBC, we should use it well. It’s a complex tool with lots of different ways to do the same thing What’s best isn’t always obvious The goals for “Best Practices”: Performance Maintainability PortabilityApril 21, 2004 © 2004, Derek C. Ashmore
  5. 5. Agenda Best Practices Practices applicable to all types of Java/JDBC code used with Oracle databases Practices targeted at Servlets, Enterprise Beans, Web Services Common Questions Latest Developments with JDBC 3.0 Future DirectionsApril 21, 2004 © 2004, Derek C. Ashmore
  6. 6. Best Practices Summary Close JDBC Objects in a “finally” block. Turn off auto-commit for select activity Audit use of platform-specific features. Always specify column lists in select and insert statements. Consider statement batching Consider query fetch sizingApril 21, 2004 © 2004, Derek C. Ashmore
  7. 7. Best Practices Summary (con’t) Reference java.sql or javax.sql classes only Avoid vendor-specific class implementations Utilize connection pooling features Closing connections are imperative ns connectionconnection leak. will create a to the poolApril 21, 2004 © 2004, Derek C. Ashmore
  8. 8. Best Practices Summary (con’t) Use Timestamp objects as host variables instead of Strings for DATE columns Consolidate SQL string formation. Separate JDBC code from business logicApril 21, 2004 © 2004, Derek C. Ashmore
  9. 9. Close all JDBC Objects Close all JDBC Objects in a finally block Stranded JDBC consume scarce db resources Cause errors down the line Oracle Cursors are consumed Usually closed in the method that creates them. As the rate stranded objects accumulate is less in development, you may not see problems caused by this until stress testing or production.April 21, 2004 © 2004, Derek C. Ashmore
  10. 10. Closure Issues Close() throws a SQLException Leads to nested try/catch logic in the finally block A lot to type Use generic close utility that logs SQLExceptions received, but doesn’t throw an exception Gets the close down to one line. CementJ – http://sourceforge.net/projects/cementj org.cementj.util.DatabaseUtilityApril 21, 2004 © 2004, Derek C. Ashmore
  11. 11. Closure Issues (con’t) Finding Stranded JDBC Objects Problematic Use P6Spy with an extension library Will identify all stranded objects and list SQL statements associated with them. P6Spy available at http://www.p6spy.com/ Extensions at “Resources” link from www.dvtpress.com/javaarchApril 21, 2004 © 2004, Derek C. Ashmore
  12. 12. Turn off auto-commit for select activity Oracle does not issue locks on reads unless you specify the “for update” clause Commits cause an extra network round- trip I turn off auto-commit for most applications. Too hard to manage when it’s on vs. offApril 21, 2004 © 2004, Derek C. Ashmore
  13. 13. Audit use of Platform-specific features Only use when clear benefit – not out of habit Creates a portability obstacle Your code might live longer than you think (Y2K). Examples Stored procedures written in PL/SQL Proprietary Column Functions Oracle’s Decode Proprietary Operators Oracle’s Minus and IntersectApril 21, 2004 © 2004, Derek C. Ashmore
  14. 14. Specify Column Lists Always specify column lists in select and insert statements. Code won’t break if DBA changes column order Clearer for maintenance purposes Imagine a select or insert statement involving 20-30 columns Hard to tell which value pertains to which columnApril 21, 2004 © 2004, Derek C. Ashmore
  15. 15. Use Statement Batching Groups updates, inserts, and deletes together in groups Has Fewer network round-trips like Stored Procedure use does. Most benefit using batches of 10 to 100 – diminishing returns after that. Larger benefit reducing network trips from 100,000 to 1,000 than from 100,000 to 100. The larger the batch, the more memory required on the client. I’ve seen Insert of 1000 rows improve from 780 ms to 50 ms!April 21, 2004 © 2004, Derek C. Ashmore
  16. 16. Set the query fetch size Instruct database to return rows in batches of 10 to 100. Has Fewer network round-trips Most benefit using batches of 10 to 100 – diminishing returns after that. Larger benefit reducing network trips from 100,000 to 1,000 than from 100,000 to 100. The larger the batch, the more memory required. More benefit with larger ResultSets I’ve seen 50% performance improvementsApril 21, 2004 © 2004, Derek C. Ashmore
  17. 17. Reference java.sql or javax.sql classes only Avoid direct use of Oracle-specific class implementations Usually not necessary now Was necessary in early days before formal support for Fetch sizing/Array Processing Statement Batching Creates a portability issue Harder to switch databases Creates a maintenance issue The JDBC interfaces are familiar Oracle-specific objects may not beApril 21, 2004 © 2004, Derek C. Ashmore
  18. 18. Utilize Connection Pooling Connection Pools eliminate wait time for database connections by creating them ahead of time. I’ve seen enough J2EE apps managing connection creation directly to warrant this practice. Connections take 30 - 50 ms depending on platform. Allows for capacity planning of database resources Provides automatic recovery from database or network outages Issuing close() on a pooled connection merely returns it to the pool for use by another request.April 21, 2004 © 2004, Derek C. Ashmore
  19. 19. Use RowId for faster updates and deletes RowId contains information about where a row physically is Used by index entries Use the rowId in the where clause for updates and deletes Faster than indexed access Easy to select the rowId Good for maintenance screens where select is usually performed before update or delete.April 21, 2004 © 2004, Derek C. Ashmore
  20. 20. Use Timestamp objects for DATE columns Oracle DATE columns contain “time” Use Timestamp for selects and as host variables for updates, inserts, and deletes Minimize converting between dates and strings It’s expensive in Java and OracleApril 21, 2004 © 2004, Derek C. Ashmore
  21. 21. Consolidate SQL String formation Some developers dynamically build the SQL string with scattered concatenation logic String sqlStmt = “select col1, col2 from tab1”; <<< more application code >>> sqlStmt = sqlStmt + “ where col2 > 200”; <<< more application code >>> sqlStmt = sqlStmt + “ and col3 < 5”; With a small number of apps, this is necessary, but most can consolidate the logic.April 21, 2004 © 2004, Derek C. Ashmore
  22. 22. Consolidate SQL String (con’t) Advantages Easier to read Saves String Processing Saves Memory Example public static final String CUST_SQL= “select name from Cust where id = ?”; …….. pStmt = conn.prepareStatement(CUST_SQL)April 21, 2004 © 2004, Derek C. Ashmore
  23. 23. Separate JDBC code from business logic Make it a separate package com.jmu.myapp.data Easier to share database access code between business functions or multiple applications Easier to port Easier to locate and changeApril 21, 2004 © 2004, Derek C. Ashmore
  24. 24. Common Questions When should I be using Stored Procedures? When should Java be inside the database instead of outside? Should I be using PreparedStatement instead of Statement?April 21, 2004 © 2004, Derek C. Ashmore
  25. 25. Stored Procedure Use Aren’t Stored Procedures better performing? Depends on platform Sybase – yes, Oracle/DB2 – not always As a general rule, CPU intensive actions are bad as stored procedures As a rule, stored procedures help performance by reducing the number of network transmissions. Conditional selects or updates As a batch update surrogate (combining larger numbers of SQL statements) Ask: How many network transmissions will be saved by making this a stored procedure? If the answer is “0”, performance is not likely to be improved.April 21, 2004 © 2004, Derek C. Ashmore
  26. 26. PreparedStatement Use PreparedStatements are recommended for most cases Statements can be faster from the client perspective For SQL not needed data type formatting for the where clause (e.g. DATE columns) For SQL with few repetitions Eliminates shared pool optimizations Will decrease database efficiency for the entire instanceApril 21, 2004 © 2004, Derek C. Ashmore
  27. 27. PreparedStatement Caching Oracle has the ability to cache PreparedStatements on the client side This is an Oracle-specific feature that will create a portability issue To use issue two statements ((OracleConnection)con).setStatementCacheSize(10); ((OracleConnection)con).setExplicitCachingEnabled(true); About 33% improvement over 100 statement testApril 21, 2004 © 2004, Derek C. Ashmore
  28. 28. Latest Developments JDBC 3.0 Specification Standardizes Connection Pooling Adds PreparedStatement pooling Savepoint support Not yet supported by Oracle Return generated PK value on insert. ResultSet Holdability – exist through commits Support multiple ResultSets for stored procedure fansApril 21, 2004 © 2004, Derek C. Ashmore
  29. 29. Future Directions JDBC is a maturing spec Expect frequency of change to slow considerably Use of Object-Relational mapping toolsets is increasing Hibernate (www.hibernate.org) JDO (www.jdocentral.com) Despite technical advances, entity beans are close to becoming a part of history.April 21, 2004 © 2004, Derek C. Ashmore
  30. 30. Questions Derek C. Ashmore Author of The J2EE™ Architect’s Handbook Downloadable at: http://www.dvtpress.com/javaarch Can be reached at dashmore@dvt.comApril 21, 2004 © 2004, Derek C. Ashmore

×