SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
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.com

April 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 it

April 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
            Portability


April 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 Directions

April 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 sizing
April 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 pool



April 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 logic



April 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.DatabaseUtility
April 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/javaarch


April 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. off

April 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 Intersect

April 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 column



April 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 improvements

April 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 be

April 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 Oracle

April 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 change

April 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 instance


April 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 test
April 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 fans

April 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 dashmore@dvt.com


April 21, 2004        © 2004, Derek C. Ashmore

Más contenido relacionado

La actualidad más candente

Dao pattern
Dao patternDao pattern
Dao patternciriako
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
Real World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesReal World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesSteve_Zavocki
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
JPA and Coherence with TopLink Grid
JPA and Coherence with TopLink GridJPA and Coherence with TopLink Grid
JPA and Coherence with TopLink GridJames Bayer
 
Create non-cdb (traditional) oracle database 12c on windows
Create non-cdb (traditional) oracle database 12c on windowsCreate non-cdb (traditional) oracle database 12c on windows
Create non-cdb (traditional) oracle database 12c on windowsBiju Thomas
 
Java EE 7 for WebLogic 12c Developers
Java EE 7 for WebLogic 12c DevelopersJava EE 7 for WebLogic 12c Developers
Java EE 7 for WebLogic 12c DevelopersBruno Borges
 
IaC MeetUp Active Directory Setup for Oracle Security LAB
IaC MeetUp Active Directory Setup for Oracle Security LABIaC MeetUp Active Directory Setup for Oracle Security LAB
IaC MeetUp Active Directory Setup for Oracle Security LABStefan Oehrli
 
Best practices for_large_oracle_apps_r12_implementations
Best practices for_large_oracle_apps_r12_implementationsBest practices for_large_oracle_apps_r12_implementations
Best practices for_large_oracle_apps_r12_implementationsAjith Narayanan
 
Working with Oracle Queues - Choosing between AQ and JMS
Working with Oracle Queues - Choosing between AQ and JMSWorking with Oracle Queues - Choosing between AQ and JMS
Working with Oracle Queues - Choosing between AQ and JMSRevelation Technologies
 
Exadata and the Oracle Optimizer: The Untold Story
Exadata and the Oracle Optimizer: The Untold StoryExadata and the Oracle Optimizer: The Untold Story
Exadata and the Oracle Optimizer: The Untold StoryEnkitec
 
REST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using RESTREST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using RESTChristian Gohmann
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivityweb360
 
Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Sander Mak (@Sander_Mak)
 

La actualidad más candente (19)

Dao pattern
Dao patternDao pattern
Dao pattern
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Real World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesReal World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPages
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
JPA and Coherence with TopLink Grid
JPA and Coherence with TopLink GridJPA and Coherence with TopLink Grid
JPA and Coherence with TopLink Grid
 
Persistence hibernate
Persistence hibernatePersistence hibernate
Persistence hibernate
 
Create non-cdb (traditional) oracle database 12c on windows
Create non-cdb (traditional) oracle database 12c on windowsCreate non-cdb (traditional) oracle database 12c on windows
Create non-cdb (traditional) oracle database 12c on windows
 
Connection Pooling
Connection PoolingConnection Pooling
Connection Pooling
 
Java EE 7 for WebLogic 12c Developers
Java EE 7 for WebLogic 12c DevelopersJava EE 7 for WebLogic 12c Developers
Java EE 7 for WebLogic 12c Developers
 
IaC MeetUp Active Directory Setup for Oracle Security LAB
IaC MeetUp Active Directory Setup for Oracle Security LABIaC MeetUp Active Directory Setup for Oracle Security LAB
IaC MeetUp Active Directory Setup for Oracle Security LAB
 
Best practices for_large_oracle_apps_r12_implementations
Best practices for_large_oracle_apps_r12_implementationsBest practices for_large_oracle_apps_r12_implementations
Best practices for_large_oracle_apps_r12_implementations
 
Working with Oracle Queues - Choosing between AQ and JMS
Working with Oracle Queues - Choosing between AQ and JMSWorking with Oracle Queues - Choosing between AQ and JMS
Working with Oracle Queues - Choosing between AQ and JMS
 
Exadata and the Oracle Optimizer: The Untold Story
Exadata and the Oracle Optimizer: The Untold StoryExadata and the Oracle Optimizer: The Untold Story
Exadata and the Oracle Optimizer: The Untold Story
 
REST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using RESTREST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using REST
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
Less18 support
Less18 supportLess18 support
Less18 support
 
Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)Hibernate Performance Tuning (JEEConf 2012)
Hibernate Performance Tuning (JEEConf 2012)
 

Destacado

Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30Derek Ashmore
 
Refactoring Into Microservices 2016-11-08
Refactoring Into Microservices 2016-11-08Refactoring Into Microservices 2016-11-08
Refactoring Into Microservices 2016-11-08Derek Ashmore
 
AWS Lambda Deployments: Best Practices and Common Mistakes O'Reilly Software...
AWS Lambda Deployments:  Best Practices and Common Mistakes O'Reilly Software...AWS Lambda Deployments:  Best Practices and Common Mistakes O'Reilly Software...
AWS Lambda Deployments: Best Practices and Common Mistakes O'Reilly Software...Derek Ashmore
 
Microservices for Java Architects (Indianapolis, April 15, 2015)
Microservices for Java Architects (Indianapolis, April 15, 2015)Microservices for Java Architects (Indianapolis, April 15, 2015)
Microservices for Java Architects (Indianapolis, April 15, 2015)Derek Ashmore
 
Microservices for architects los angeles-2016-07-16
Microservices for architects los angeles-2016-07-16Microservices for architects los angeles-2016-07-16
Microservices for architects los angeles-2016-07-16Derek Ashmore
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Derek Ashmore
 
Refactoring Into Microservices 2016-11-06
Refactoring Into Microservices 2016-11-06Refactoring Into Microservices 2016-11-06
Refactoring Into Microservices 2016-11-06Derek Ashmore
 
Aws Lambda for Java Architects - JavaOne -2016-09-19
Aws Lambda for Java Architects - JavaOne -2016-09-19Aws Lambda for Java Architects - JavaOne -2016-09-19
Aws Lambda for Java Architects - JavaOne -2016-09-19Derek Ashmore
 
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02Derek Ashmore
 
An Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI CompositionAn Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI CompositionDr. Arif Wider
 

Destacado (10)

Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30
 
Refactoring Into Microservices 2016-11-08
Refactoring Into Microservices 2016-11-08Refactoring Into Microservices 2016-11-08
Refactoring Into Microservices 2016-11-08
 
AWS Lambda Deployments: Best Practices and Common Mistakes O'Reilly Software...
AWS Lambda Deployments:  Best Practices and Common Mistakes O'Reilly Software...AWS Lambda Deployments:  Best Practices and Common Mistakes O'Reilly Software...
AWS Lambda Deployments: Best Practices and Common Mistakes O'Reilly Software...
 
Microservices for Java Architects (Indianapolis, April 15, 2015)
Microservices for Java Architects (Indianapolis, April 15, 2015)Microservices for Java Architects (Indianapolis, April 15, 2015)
Microservices for Java Architects (Indianapolis, April 15, 2015)
 
Microservices for architects los angeles-2016-07-16
Microservices for architects los angeles-2016-07-16Microservices for architects los angeles-2016-07-16
Microservices for architects los angeles-2016-07-16
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15
 
Refactoring Into Microservices 2016-11-06
Refactoring Into Microservices 2016-11-06Refactoring Into Microservices 2016-11-06
Refactoring Into Microservices 2016-11-06
 
Aws Lambda for Java Architects - JavaOne -2016-09-19
Aws Lambda for Java Architects - JavaOne -2016-09-19Aws Lambda for Java Architects - JavaOne -2016-09-19
Aws Lambda for Java Architects - JavaOne -2016-09-19
 
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
 
An Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI CompositionAn Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI Composition
 

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

Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)sheriframadan18
 
Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...
Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...
Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...Juarez Junior
 
EMC Multisite DR for SQL Server 2012
EMC Multisite DR for SQL Server 2012EMC Multisite DR for SQL Server 2012
EMC Multisite DR for SQL Server 2012xKinAnx
 
configuring+oracle+rds+with+glasfish+server
configuring+oracle+rds+with+glasfish+serverconfiguring+oracle+rds+with+glasfish+server
configuring+oracle+rds+with+glasfish+serverhunghtc83
 
BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...
BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...
BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...Juarez Junior
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part ISivaSankari36
 
DWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual Threads
DWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual ThreadsDWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual Threads
DWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual ThreadsJuarez Junior
 
CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...
CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...
CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...Juarez Junior
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkBill Lyons
 
SQLCLR For DBAs and Developers
SQLCLR For DBAs and DevelopersSQLCLR For DBAs and Developers
SQLCLR For DBAs and Developerswebhostingguy
 
Dr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. HydeDr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. Hydewebhostingguy
 
CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...
CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...
CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...Juarez Junior
 
DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...
DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...
DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...Juarez Junior
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3Oracle
 

Similar a Jdbc Best Practices - Oracle/IOUG, Toronto, April 21, 2004 (20)

Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
 
Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...
Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...
Cloud Conference Day - A High-Speed Data Ingestion Service in Java Using MQTT...
 
EMC Multisite DR for SQL Server 2012
EMC Multisite DR for SQL Server 2012EMC Multisite DR for SQL Server 2012
EMC Multisite DR for SQL Server 2012
 
configuring+oracle+rds+with+glasfish+server
configuring+oracle+rds+with+glasfish+serverconfiguring+oracle+rds+with+glasfish+server
configuring+oracle+rds+with+glasfish+server
 
BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...
BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...
BarcelonaJUG - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, ...
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 
DWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual Threads
DWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual ThreadsDWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual Threads
DWX23 - Revolutionize Java DB AppDev with Reactive Streams and Virtual Threads
 
CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...
CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...
CloudLand - Revolutionize Java DB AppDev with Reactive Streams and Virtual Th...
 
Ef code first
Ef code firstEf code first
Ef code first
 
Data access
Data accessData access
Data access
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
SQLCLR For DBAs and Developers
SQLCLR For DBAs and DevelopersSQLCLR For DBAs and Developers
SQLCLR For DBAs and Developers
 
Dr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. HydeDr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. Hyde
 
Day4
Day4Day4
Day4
 
CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...
CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...
CloudLand - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and...
 
6 database
6 database 6 database
6 database
 
DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...
DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...
DWX23 - A High-Speed Data Ingestion Service in Java Using MQTT, AMQP, and STO...
 
Jdbc
JdbcJdbc
Jdbc
 
PHP Oracle
PHP OraclePHP Oracle
PHP Oracle
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
 

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 dashmore@dvt.com April 21, 2004 © 2004, Derek C. Ashmore
  • 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. 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 it April 21, 2004 © 2004, Derek C. Ashmore
  • 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 Portability April 21, 2004 © 2004, Derek C. Ashmore
  • 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 Directions April 21, 2004 © 2004, Derek C. Ashmore
  • 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 sizing April 21, 2004 © 2004, Derek C. Ashmore
  • 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 pool April 21, 2004 © 2004, Derek C. Ashmore
  • 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 logic April 21, 2004 © 2004, Derek C. Ashmore
  • 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. 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.DatabaseUtility April 21, 2004 © 2004, Derek C. Ashmore
  • 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/javaarch April 21, 2004 © 2004, Derek C. Ashmore
  • 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. off April 21, 2004 © 2004, Derek C. Ashmore
  • 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 Intersect April 21, 2004 © 2004, Derek C. Ashmore
  • 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 column April 21, 2004 © 2004, Derek C. Ashmore
  • 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. 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 improvements April 21, 2004 © 2004, Derek C. Ashmore
  • 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 be April 21, 2004 © 2004, Derek C. Ashmore
  • 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. 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. 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 Oracle April 21, 2004 © 2004, Derek C. Ashmore
  • 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. 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. 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 change April 21, 2004 © 2004, Derek C. Ashmore
  • 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. 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. 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 instance April 21, 2004 © 2004, Derek C. Ashmore
  • 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 test April 21, 2004 © 2004, Derek C. Ashmore
  • 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 fans April 21, 2004 © 2004, Derek C. Ashmore
  • 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. Questions Derek C. Ashmore Author of The J2EE™ Architect’s Handbook Downloadable at: http://www.dvtpress.com/javaarch Can be reached at dashmore@dvt.com April 21, 2004 © 2004, Derek C. Ashmore