Boiler Plating Database Resource Cleanup With Execute Around Method ACCU London February 2009 ACCU Conference April 2009 Validus 8 Thorpe Road Norwich.

Slides:



Advertisements
Similar presentations
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Advertisements

Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
Advanced Java Programming – Eran Toch Methodologies in Information System Development Tutorial: Advanced Java Programming and Database connection Eran.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
CIS 270—App Dev II Big Java Chapter 22 Relational Databases.
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
JDBC and Hibernate Joshua Scotton. Connecting to Relational DBs.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
Anti Orgla, Nortal AS Spring Framework
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
CS 405G: Introduction to Database Systems Database programming.
1 KC Web & Java – 29 november 2005 – Design Patterns – The Template Method AJAX! KC Web & Java 29 november 2005.
Object Oriented Programming in PHP. Topics Quick OOP Review Classes Magic Methods Static Methods Inheritance Exceptions Interfaces Operators Type Hinting.
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
CS 160: Software Engineering October 1 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Partitioning Patterns How to partition complex actors and concepts into multiple classes. Layered Initialization Filter Composite.
Chapter 8 Databases.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
MySQL & JDCB Αλέξανδρος Καρακασίδης Δεκέμβριος 2004.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
EXAMPLE I An application showing JDBC access to Cloudscape.
Java JDBC API. A Java API To Access almost any kind of tabular data To Access almost any kind of tabular data Trademarked (not an acronym) Trademarked.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
The OWASP Foundation OWASP Education Computer based training CERT Secure Coding Nishi Kumar IT Architect Specialist, FIS Chair, Software.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Basics of JDBC.
Database Management Systems 1 Raghu Ramakrishnan Database Application Development Chpt 6 Xin Zhang.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring JDBC Simplifying.
Web Programming Assistant Professor Xiaozhong Liu
Spring JDBC Dima Ionut Daniel. Contents What is Spring JDBC? Overview Spring JDBC Core SQL Exceptions Database Connection Batch Operations Handling BLOB/CLOB.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
JSP/Database Connectivity Instructor: Dr. M. Anwar Hossain.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Instructor: Jinze Liu Fall /8/2016Jinze University of Kentucky 2 Database Project Database Architecture Database programming.
JSP and DB.
CS3220 Web and Internet Programming Database Access with JDBC
CS320 Web and Internet Programming Database Access with JDBC
HW#4 Making Simple BBS Using JDBC
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
Introduction to Server-Side Web Development using JSP and Databases
Making Text for the Web part 6
Spring 프레임워크의 이해 5. Spring Abstract API.
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Boiler Plating Database Resource Cleanup With Execute Around Method ACCU London February 2009 ACCU Conference April 2009 Validus 8 Thorpe Road Norwich NR1 1RY Paul Grenyer Senior Software Engineer

Agenda  All About Me  The Problem (audience participation)  Execute Around Method  A solution

Speaker biography  Who am I?  My career so far  Validus-IVC and what I do there

The Problem

Audience Participation 1 Write some JDBC code to execute the following update statement: UPDATE SERVICES SET URL=" WHERE NAME = ' ' Key concept: Connection User

Creating a Connection try { Class.forName(DRIVER); final Connection con = DriverManager.getConnection( CONNECTION_STRING, USERNAME, PASSWORD); con.setCatalog(DATABASE); // Use connection } catch(ClassNotFoundException e) { // handle error } catch(SQLException e) { // handle error }

Creating and using a Statement... final Statement stmt = con.createStatement(); try { stmt.execute(SQL); } finally { try { stmt.close(); } catch(SQLException e) { // handle error }...

Wouldn't it be nicer if you could do this? try { final ConnectionProvider cp = new ConnectionProvider(new StringConnection(DRIVER, CONNECTION_STRING).setUser(USERNAME,PASSWORD).setDatabase(DATABASE)); Query.execute( cp, "UPDATE … WHERE NAME = ' '"); } catch(Exception e) { // Report error }

Audience Participation 2 Write some JDBC code to execute the following select statement: SELECT URL FROM SERVICES and write the result to the console Key concept: Connection Value

Creating and using a Result Set... final Statement stmt = con.createStatement(); try { final ResultSet rs = stmt.executeQuery(SQL); try { while(rs.next()) { System.out.println(rs.getString("url")); } finally { try { rs.close(); } catch(Exception e) { // Handle exception }...

Wouldn't it be nicer if you could do this? try { final ConnectionProvider cp = new ConnectionProvider(new StringConnection(DRIVER,CONNECTION_STRING).setUser(USERNAME, PASSWORD).setDatabase(DATABASE)); final List urls = Query.execute( cp, "SELECT URL FROM SERVICES", new RSProcessor()); for(String url : urls) { System.out.println(url); } catch(Exception e) { e.printStackTrace(); }

Wouldn't it be nicer if you could do this? class RSProcessor extends AbstractResultSetFunction > public List read(ResultSet rs) { List result = new ArrayList (); try { while (rs.next()) { result.add(rs.getString("url")); } catch(SQLException ex) { getErrorPolicy().handleError(ex); } return result; }

Execute Around Method (EAM) “Encapsulate pairs of actions in the object that requires them, not code that uses the object, and pass usage code to the object as another object.” Kevlin Henney ?

File Writer

public interface WriterUser { void use(Writer writer) throws IOException ; } public class FileWriterProvider { private final String filename; public FileWriterProvider(String filename) { this.filename = filename; } public void provideTo(WriterUser user) throws IOException { final FileWriter writer = new FileWriter(filename); try { user.use(writer); } finally { writer.close(); }

new FileWriterProvider("out.txt").provideTo(new WriterUser() public void use(Writer writer) throws IOException { writer.write("Execute Around Method!"); } });

Execute Around Method (EAM) “Using an object to manage a resource and provide it to another object to use”

The Solution  Resource management  Providers (inc. connection factory) & Users  Error handling

Resource Management Resources to manage:  Connection  Statement  ResultSet Each must be:  Acquired  Used  Cleaned-up

Connection Provider > Statement Provider > ResultSet Provider >

Connection Provider The concept of a connection provider was suggested to me by Adrian Fagg. The idea is that:  A single class is responsible for acquiring a connection  Providing it to another class for use  Releasing it again Execute Around Method!

Connection Provider

Connection Factory Interface public interface ConnectionFactory { Connection connect(); void disconnect(Connection con); } Why have a connection factory?  On demand connection  Connection pool  Existing connection  Custom connection

Connection Factory: disconnect public abstract class AbstractConnectionFactory implements ConnectionFactory public void disconnect(Connection con) { if (con != null) { try { con.close(); } catch(final SQLException ex) { // To do }  A Connection can be created any number of ways.  A Connection is usually closed in the same way.

Connection Factory: connect public Connection connect() { Connection con = null; try { Class.forName(driver); con = DriverManager.getConnection( connectionString, username, password); } catch(ClassNotFoundException ex) { // To do } catch(SQLException ex) { // To do } return con; }

Connection Provider: Construction public final class ConnectionProvider { private final ConnectionFactory conFactory; public ConnectionProvider(ConnectionFactory conFactory) { this.conFactory = conFactory; }

Key Concepts User: An object that uses a JDBC resource, but doesn’t return a value. public interface ConnectionUser { void use(Connection con); } Value User: An object that uses a JDBC resource and returns a value. public interface ConnectionValue { T fetch(Connection con); }

Connection User Interface public interface ConnectionUser { void use(Connection con); }  Uses the connection  Does not return a value!

Connection Provider: User public void provideTo( ConnectionUser user ) { final Connection con = conFactory.connect(); try { user.use(con); } finally { conFactory.disconnect(con); }  Uses Finally for Each Release Pattern to:  Create a Connection from the factory  Passes the Connection to the user  Closes Connection

Connection Value User public interface ConnectionValue { T fetch(Connection con); } Like the ConnectionUser, but:  Fetch method has a return type  Return type is a generic parameter

Connection Provider: Value User public T provideTo( ConnectionValue valueUser ) { final Connection con = conFactory.connect(); T result = null; try { result = valueUser.fetch(con); } finally { conFactory.disconnect(con); } return result; }  Uses Finally for Each Release pattern to:  Create a Connection from the factory  Passes the Connection to the user and stores the result  Closes connection  Passes the result back.

Statement Provider

Statement User and Value User public interface StatementUser { void use(Statement stmt); } public interface StatementValue { T use(Statement stmt); }

Statement Provider: Value User public T provideTo( StatementValue valueUser ) { T result = null; try { final Statement stmt = con.createStatement(); try { result = valueUser.use(stmt); } finally { try { stmt.close(); } catch(SQLException ex) { // To do } catch(SQLException ex) { // To do } return result; }

Result Set Provider

ResultSetFunction public interface ResultSetFunction { T read(ResultSet rs); }  Iterates through RecordSet.  Returns result.

ResultSet Provider public T provideTo(ResultSetFunction fetcher) { T result = null; try { final ResultSet rs = stmt.executeQuery(sql); try { result = fetcher.read(rs); } finally { try { rs.close(); } catch(Exception ex) { // To do } catch(SQLException ex) { // To do } return result; }

Connection Provider > Statement Provider > ResultSet Provider > Putting It All Together.

Error Policy A common error policy allows the client to decide how to handle errors: public interface ErrorPolicy { void handleError(Exception ex) void handleCleanupError(Exception ex) }  Clean-up exceptions could be handled differently  May be logged, rather than re-thrown  Decision can be made by the client

public T provideTo( StatementValue valueUser ) { T result = null; try { final Statement stmt = con.createStatement(); try { result = valueUser.use(stmt); } finally { try { stmt.close(); } catch(SQLException ex) { // handle clean-up exception } catch(SQLException ex) { // Handle exception } return result; }

To Check or Not To Check Checked Exceptions  Interface methods can throw Exception.  Interface methods can throw a custom exception that all checked exceptions must be translated into. public interface ErrorPolicy { void handleError(Exception ex) throws Exception; void handleCleanupError(Exception ex) throws Exception; } public interface ErrorPolicy { void handleError(Exception ex) throws CustomException; void handleCleanupError(Exception ex) throws CustomException; }

To Check or Not To Check Runtime Exceptions  The implementer of the interface is forced to translate checked exceptions to runtime exceptions. public interface ErrorPolicy { void handleError(Exception ex) void handleCleanupError(Exception ex) }

Default Error Policy public class DefaultErrorPolicy implements ErrorPolicy { private Exception firstException = public void handleCleanupError(Exception ex) { handleError(ex); public void handleError(Exception ex) { if (firstException == null) { firstException = ex; throw new RuntimeException(ex); }

Error Policy User public interface ErrorPolicyUser { void setErrorPolicy(ErrorPolicy errorPolicy); }  All classes that use an ErrorPolicy must implement the ErrorPolicyUser interface.  The ErrorPolicyUser is used by providers to pass an ErrorPolicy to its User s and Value s (dependency injection).  All User s and Value s must therefore be an ErrorPolicyUser.

public interface ConnectionFactory extends ErrorPolicyUser { Connection connect(); void disconnect(Connection con); } public interface ConnectionUser extends ErrorPolicyUser { void use(Connection con); } public interface ConnectionValue extends ErrorPolicyUser { T fetch(Connection con); } public interface StatementUser extends ErrorPolicyUser { void use(Statement stmt); } public interface StatementValue extends ErrorPolicyUser { T use(Statement stmt); } public interface ResultSetFunction extends ErrorPolicyUser { T read(ResultSet rs); }

public final class StatementProvider { public void provideTo( StatementUser user ) { user.setErrorPolicy(errorPolicy); try { final Statement stmt = con.createStatement(); try { user.use(stmt); } finally { try { stmt.close(); } catch(SQLException ex) { errorPolicy.handleCleanupError(ex); } catch(SQLException ex) { errorPolicy.handleError(ex); }

Common Error Policy User public abstract class AbstractErrorPolicyUser implements ErrorPolicyUser { private ErrorPolicy errorPolicy = new DefaultErrorPolicy(); protected ErrorPolicy getErrorPolicy() { return errorPolicy; public void setErrorPolicy(ErrorPolicy errorPolicy) { this.errorPolicy = errorPolicy; }  The CommonErrorPolicyUser provides a common:  ErrorPolicy set method  ErrorPolicy reference  ErrorPolicy accessor

Composition  Unnecessary ErrorPolicyUser reference.  Unnecessary set/get ErrorPolicy methods implemented in ConcreteUser.

Inheritance  ConcreteConnection inherits set/get methods for free.  ConecreteConnection IS-A ErrorPolicyUser

public class Execute extends AbstractErrorPolicyUser implements StatementUser public void use(Statement stmt) { try { for(String s : sql) { stmt.execute(s); } catch(SQLException ex) { getErrorPolicy().handleError(ex); }

Sorted!

Connection Provider > Statement Provider > ResultSet Provider >

Reminder try { final ConnectionProvider cp = new ConnectionProvider(new StringConnection(DRIVER,CONNECTION_STRING).setUser(USERNAME, PASSWORD).setDatabase(DATABASE)); final List urls = Query.execute( cp, "SELECT URL FROM SERVICES", new RSProcessor()); for(String url : urls) { System.out.println(url); } catch(Exception e) { e.printStackTrace(); }

Reminder class RSProcessor extends AbstractResultSetFunction > public List read(ResultSet rs) { List result = new ArrayList (); try { while (rs.next()) { result.add(rs.getString("url")); } catch(SQLException ex) { getErrorPolicy().handleError(ex); } return result; }

Anymore questions? See you in the bar… Validus 8 Thorpe Road Norwich NR1 1RY Paul Grenyer Senior Software Engineer