Tips & Tricks
Jdbc Best Practices - Oracle/IOUG, Toronto, April 21, 2004
Like this document? Why not share!
Quadernet sitges i carboners
Antequera Monumental y Cultural
by Turismo de Antequera
USGS Spring Clark Fork River Water...
by Clark Fork Task F...
2 3 user virality-성공_전략(최종)
by Cyworld AppStore ...
by Néstor González S...
by kenji sakuma
Email sent successfully!
Show related SlideShares at end
Jdbc Best Practices - Oracle/IOUG, Toronto, April 21, 2004
Jan 04, 2012
Comment goes here.
12 hours ago
Are you sure you want to
Your message goes here
Be the first to comment
Be the first to like this
Number of Embeds
No notes for slide
Transcript of "Jdbc Best Practices - Oracle/IOUG, Toronto, April 21, 2004"
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 email@example.comApril 21, 2004 © 2004, Derek C. Ashmore
Data Access Options JDBC SQL/J J2EE Entity Beans Object-Relational Mapping Toolsets Hibernate JDO Many others…..April 21, 2004 © 2004, Derek C. Ashmore
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Questions Derek C. Ashmore Author of The J2EE™ Architect’s Handbook Downloadable at: http://www.dvtpress.com/javaarch Can be reached at firstname.lastname@example.orgApril 21, 2004 © 2004, Derek C. Ashmore