SlideShare a Scribd company logo
1 of 100
JDBC and Data Access Objects
Goals ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object]
Data Access Object (DAO) Pattern
Context and Problem ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Forces ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Solution ,[object Object]
DAO Pattern Interactions
DAO Pattern Roles ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DAO Factory Strategy ,[object Object]
DAO Factory Structure
Consequences ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DAO Interface package ejava.examples.dao; import java.util.Collection; import ejava.examples.dao.domain.Book ; public interface BookDAO { Book create(Book book)  throws DAOException ; Book update(Book book) throws DAOException; Book get(long id) throws DAOException; boolean remove(Book book) throws DAOException; Collection<Book> findAll(long start, long count)  throws DAOException; }
DAO Implementation package ejava.examples.dao.jdbc; ... import ejava.examples.dao.BookDAO; import ejava.examples.dao.DAOException; import ejava.examples.dao.domain.Book; public class JDBCBookDAO extends JDBCDAOBase  implements BookDAO  { public Book create(Book book) throws DAOException { ... public Book update(Book book) throws DAOException { ... public Book get(long id) throws DAOException { ... public boolean remove(Book book) throws DAOException { ... public Collection<Book> findAll(int start, int count)  throws DAOException { ... }
Wrapped Exceptions package ejava.examples.dao; public class DAOException extends Exception { private static final long serialVersionUID = 1L; public DAOException() {} public DAOException(String message) { super(message); } public DAOException(String message, Throwable rootCause) { super(message, rootCause); } public DAOException(Throwable rootCause) { super(rootCause); } } try { ... } catch (<T> ex) { throw new DAOException(“troubles”, ex); } * be careful that Resource Level Exception is not  propogated all the way back to remote client. May cause ClassNotFoundExceptions
Relating Business Objects to  Data Transfer Objects (DTOs)
DTO Pattern ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DTO/Remote Facade Solution ,[object Object],[object Object],[object Object]
DTO Pattern Roles ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DTO Pattern Consequences ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Relational Databases and SQL
Relational Database and SQL Review ,[object Object],[object Object],[object Object]
Relational Databases ,[object Object],[object Object],[object Object]
SQL ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Common SQL Operations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Image Table IMAGE_ID IMAGE_TYPE FILENAME URL 1 gif image1 http://host/dir/image1 2 gif image2 ftp://host/dir/image2
Image Decoder Table IMAGE_TYPE DECODER_PROGRAM LIC_START LIC_END gif c:ifdecoder 12/01/1998 12/01/1999 jpg d:oolspgdecoder 06/01/1999 12/01/2010
Tables and Keys Primary Keys Foreign Key DECODER DECODER IMAGE IMAGE_ID  IMAGE_TYPE  FILENAME  URL 1 gif Image1 … ... IMAGE_TYPE DECODER_PROGRAM gif c:ifdecoder … ...
Example Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Creating Tables ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Image Tables (Cont) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Adding constraints ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
NULLs ,[object Object],[object Object],[object Object]
Primary Keys ,[object Object],[object Object],[object Object],[object Object],[object Object]
Foreign Keys ,[object Object],[object Object],[object Object],[object Object]
CHECK Constraint ,[object Object],[object Object]
Dropping Tables ,[object Object],[object Object]
Inserting Rows ,[object Object],[object Object],[object Object],[object Object]
Selecting Rows ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Updating Rows ,[object Object],[object Object],[object Object],[object Object],[object Object]
Deleting Rows ,[object Object],[object Object],[object Object],[object Object],[object Object]
Basic Where Clauses ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Views ,[object Object],[object Object],[object Object]
SQL Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object]
Numeric Data Types ,[object Object],[object Object]
Exact Numeric Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Approximate Numeric Data Types ,[object Object],[object Object],[object Object]
Temporal Data Types ,[object Object],[object Object],[object Object],[object Object]
Character Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Locator-Based data types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
SQL Summary ,[object Object],[object Object],[object Object]
Java Database Connectivity (JDBC)
JDBC Drivers ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Key JDBC Classes/Interfaces ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
Example Program Step 1 - Load the Driver ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Driver Loading ,[object Object],[object Object],[object Object],[object Object]
Driver Loading (cont.) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Example Program Step 2 - Obtain a Connection ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What Driver creates the Connection ? ,[object Object],[object Object],[object Object],[object Object]
JDBC URLs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
DriverManager package java.sql; public class DriverManager { public static synchronized Connection getConnection( String url, String username, String password) {... public static synchronized Connection getConnection( String url, Properties props) { ... public static synchronized Connection getConnection( String url)  public static synchronized Driver getDriver( String url) { ...  public static synchronized void registerDriver( java.sql.Driver driver) { ... public static synchronized void deregisterDriver( Driver driver) { ... public static synchronized java.util.Enumeration<Driver> getDrivers()  { ... public static void setLoginTimeout( int seconds) { ... public static java.io.PrintWriter getLogWriter()  { ... public static void setLogWriter( java.io.PrintWriter out) { ... public static void println( String message) { ...
Driver package java.sql; public interface Driver { Connection connect(String url, java.util.Properties info) throws SQLException; boolean acceptsURL(String url)  throws SQLException; DriverPropertyInfo[] getPropertyInfo( String url, java.util.Properties info) throws SQLException; int getMinorVersion(); boolean jdbcCompliant(); }
Connection package java.sql; public interface Connection { Statement createStatement() throws SQLException; PreparedStatement prepareStatement( String sql)throws SQLException; CallableStatement prepareCall( String sql) throws SQLException; PreparedStatement prepareStatement(String sql, int resultSetType,  int resultSetConcurrency)throws SQLException; CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency)  throws SQLException; Statement createStatement( int resultSetType, int resultSetConcurrency,  int resultSetHoldability) throws SQLException; PreparedStatement prepareStatement(String sql, int resultSetType,  int resultSetConcurrency, int resultSetHoldability) throws SQLException; CallableStatement prepareCall(String sql, int resultSetType,  int resultSetConcurrency,  int resultSetHoldability) throws SQLException; PreparedStatement prepareStatement( String sql, int autoGeneratedKeys) throws SQLException; PreparedStatement prepareStatement( String sql, int columnIndexes[]) throws SQLException; PreparedStatement prepareStatement( String sql, String columnNames[])throws SQLException; ...
Connection package java.sql; public interface Connection { ... void setAutoCommit( boolean autoCommit) throws SQLException; boolean getAutoCommit() throws SQLException; void commit() throws SQLException; void rollback() throws SQLException; void close() throws SQLException; boolean isClosed() throws SQLException; void setTransactionIsolation(int level) throws SQLException; int getTransactionIsolation() throws SQLException; SQLWarning getWarnings() throws SQLException; void clearWarnings() throws SQLException; Savepoint setSavepoint() throws SQLException; Savepoint setSavepoint(String name) throws SQLException; void rollback(Savepoint savepoint) throws SQLException; void releaseSavepoint(Savepoint savepoint) throws SQLException; ...
Example Program Step 3 - Execute a Query ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],accessDatabase:47)  -1, jpg, image1, http://host/dir/image1 accessDatabase:47)  -2, gif, image2, http://host/dir/image2 accessDatabase:54)  -closing resources accessDatabase:58)  -resources closed
Executing Statements ,[object Object],[object Object],[object Object]
Example Program Step 4 - Process Results ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Example Program Step 5 - Release Resources ,[object Object],[object Object],[object Object]
Statement ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Statement (Cont) ,[object Object],[object Object],[object Object],[object Object]
Statement (Cont) ,[object Object],[object Object],[object Object],[object Object]
Statement package java.sql; public interface Statement { ... ResultSet executeQuery(String sql) throws SQLException; int executeUpdate(String sql) throws SQLException; SQLWarning getWarnings() throws SQLException; void clearWarnings() throws SQLException; boolean execute(String sql) throws SQLException; ResultSet getResultSet() throws SQLException;  int getUpdateCount() throws SQLException;  boolean getMoreResults() throws SQLException;  int getResultSetType()  throws SQLException; void addBatch( String sql ) throws SQLException; void clearBatch() throws SQLException; int[] executeBatch() throws SQLException; boolean getMoreResults(int current) throws SQLException; ResultSet getGeneratedKeys() throws SQLException; int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException; int executeUpdate(String sql, int columnIndexes[]) throws SQLException; int executeUpdate(String sql, String columnNames[]) throws SQLException; boolean execute(String sql, int autoGeneratedKeys) throws SQLException; boolean execute(String sql, int columnIndexes[]) throws SQLException; boolean execute(String sql, String columnNames[]) throws SQLException; ...
Statement package java.sql; public interface Statement { ... int getMaxFieldSize() throws SQLException; void setMaxFieldSize(int max) throws SQLException; int getMaxRows() throws SQLException; void setMaxRows(int max) throws SQLException; void setEscapeProcessing(boolean enable) throws SQLException; int getQueryTimeout() throws SQLException; void setQueryTimeout(int seconds) throws SQLException; void cancel() throws SQLException; void setCursorName(String name) throws SQLException; boolean execute(String sql) throws SQLException; void setFetchDirection(int direction) throws SQLException; int getFetchDirection() throws SQLException; void setFetchSize(int rows) throws SQLException; int getFetchSize() throws SQLException; int getResultSetConcurrency() throws SQLException; void addBatch( String sql ) throws SQLException; void clearBatch() throws SQLException; Connection getConnection()  throws SQLException; ResultSet getGeneratedKeys() throws SQLException; int getResultSetHoldability() throws SQLException; ...
Prepared Statement ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Callable Statement ,[object Object],[object Object]
ResultSet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Transactions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JDBC Transaction API ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Isolation Levels ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Transaction Methods ,[object Object],[object Object],[object Object]
Savepoints ,[object Object],[object Object]
Exceptions and Warnings ,[object Object]
SQL Warning ,[object Object],[object Object],[object Object]
SQL Warning
JDBC Summary ,[object Object],[object Object],[object Object],[object Object],[object Object]
JDBC/SQL-based DAO Example
Schema create sequence DAO_BOOK_SEQ as int start with 100 increment by 1; create table DAO_BOOK_UID ( ID bigint ); insert into DAO_BOOK_UID (ID) VALUES ( NEXT VALUE FOR DAO_BOOK_SEQ ); create table DAO_BOOK ( ID  bigint not null, VERSION  bigint not null, TITLE  varchar(64), AUTHOR  varchar(64), DESCRIPTION varchar(2000), PAGES  int, CONSTRAINT dao_BookPK PRIMARY KEY(ID) );
Example DAO Test Client Connection connection; BookDAO dao; protected void setUp() throws Exception { connection = getConnection(); connection.setAutoCommit(false); JDBCBookDAO.setConnection(connection); dao = new JDBCBookDAO(); } public void testCreate() throws Exception { Book book = new Book(nextId()); book.setTitle(&quot;a&quot;); book.setAuthor(&quot;b&quot;); book.setDescription(&quot;testCreate&quot;); book.setPages(20); try { Book book2 = dao.create(book); connection.commit(); assertNotNull(book2); } catch (Exception ex) { connection.rollback(); fail(&quot;&quot; + ex); } }
Connection Sharing using ThreadLocal package ejava.examples.dao.jdbc; import java.sql.*; public class JDBCDAOBase { static ThreadLocal<Connection> connection =  new ThreadLocal<Connection>(); public static void setConnection(Connection conn) { connection.set(conn); } protected Connection getConnection()  throws IllegalStateException { Connection conn = connection.get(); if (conn == null) { throw new IllegalStateException( &quot;Connection has not been set&quot;); } return conn; }
Resource Helpers protected static void closeConnection() throws SQLException { Connection conn = connection.get(); if (conn != null) { connection.set(null); conn.close(); } } protected void close(Statement st) { try { st.close();} catch (Throwable ignored) {} } protected void close(ResultSet rs) { try { rs.close();} catch (Throwable ignored) {} }
Inserting Object  (and calling a private setter) public Book create(Book book) throws DAOException { long id = (book.getId() == 0) ? getNextId() : book.getId(); PreparedStatement st = null; try { st = getConnection().prepareStatement( &quot;INSERT INTO &quot; + TABLE_NAME + &quot; &quot; + &quot;(ID, VERSION, TITLE, AUTHOR, DESCRIPTION, PAGES) &quot; + &quot;VALUES(?, ?, ?, ?, ?, ?)&quot;); st.setLong(1, id); st.setLong(2, 0); st.setString(3, book.getTitle()); st.setString(4, book.getAuthor()); st.setString(5, book.getDescription()); st.setInt(6, book.getPages()); if (st.executeUpdate() != 1) { throw new DAOException(&quot;unable to insert Book&quot;);  } book.setVersion(0); if (book.getId()==0) { //use reflection to get private setId method of Book class Method setId = Book.class.getDeclaredMethod( &quot;setId&quot;, new Class[] { int.class }); setId.setAccessible(true); setId.invoke(book, new Object[] { id }); } return book; } catch (Exception ex) { throw new DAOException(ex); } finally { close(st); } }
Generating an ID public int getNextId() throws DAOException { Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); st.executeUpdate(&quot;UPDATE DAO_BOOK_UID &quot; + &quot;SET ID=NEXT VALUE FOR DAO_BOOK_SEQ”);  rs = st.executeQuery(&quot;SELECT ID FROM DAO_BOOK_UID”); rs.next(); return rs.getInt(1);  } catch (SQLException ex) { throw new DAOException(ex); } finally { close(rs); close(st); } }
Updating Database public Book update(Book book) throws DAOException { if (book.getId() == 0) { throw new DAOException(&quot;Book does not have primary key&quot;); } PreparedStatement st = null; try { long version = getVersion(book.getId()); st = getConnection().prepareStatement(&quot;UPDATE &quot; + TABLE_NAME + &quot; &quot; + &quot;SET VERSION=?, TITLE=?, AUTHOR=?, DESCRIPTION=?, PAGES=? &quot; + &quot;WHERE ID=?&quot;); st.setLong(1, ++version); st.setString(2, book.getTitle()); st.setString(3, book.getAuthor()); st.setString(4, book.getDescription()); st.setInt(5, book.getPages()); st.setLong(6, book.getId()); int count = st.executeUpdate(); if (count == 0) { throw new DAOException(&quot;Object not found:&quot; + book.getId()); } book.setVersion(version); return book; } catch (SQLException ex) { throw new DAOException(ex);  } finally { close(st); } }
Getting Version (Helper) protected long getVersion(long id) throws SQLException, DAOException { long version = 0; Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); rs = st.executeQuery(&quot;SELECT VERSION FROM &quot; +  TABLE_NAME + &quot; WHERE ID=&quot; + id); if (!rs.next()) { throw new DAOException(&quot;Object not found&quot;); } version = rs.getLong(1); } finally { close(rs); close(st); } return version; }
Getting Object By ID public Book get(long id) throws DAOException { Book book = null; Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); rs = st.executeQuery( &quot;SELECT VERSION, AUTHOR, TITLE, DESCRIPTION, PAGES &quot; + &quot;FROM &quot; + TABLE_NAME + &quot; &quot; + &quot;WHERE ID=&quot; + id); if (!rs.next()) { throw new DAOException(&quot;Object not found&quot;); } book = new Book(id); book.setVersion(rs.getLong(1)); book.setAuthor(rs.getString(2)); book.setTitle(rs.getString(3)); book.setDescription(rs.getString(4)); book.setPages(rs.getInt(5)); return book; } catch (SQLException ex) { throw new DAOException(ex); } finally { close(rs); close(st); } }
Removing Object public boolean remove(Book book) throws DAOException { Statement st = null; try { st = getConnection().createStatement(); int count = st.executeUpdate(&quot;DELETE FROM &quot; + TABLE_NAME + &quot; WHERE ID=&quot; + book.getId()); return count == 1; } catch (SQLException ex) { throw new DAOException(ex); } finally { close(st); } }
Finding Objects public Collection<Book> findAll(int start, int count)  throws DAOException { Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = st.executeQuery(&quot;SELECT * FROM &quot; + TABLE_NAME); Collection<Book> collection = new ArrayList<Book>(); rs.absolute(start); int i=0; while (rs.next() && i++<count) { Book b = new Book(rs.getLong(&quot;ID&quot;)); b.setAuthor(rs.getString(&quot;AUTHOR&quot;)); b.setDescription(rs.getString(&quot;DESCRIPTION&quot;)); b.setPages(rs.getInt(&quot;PAGES&quot;)); b.setTitle(rs.getString(&quot;TITLE&quot;)); b.setVersion(rs.getLong(&quot;VERSION&quot;)); collection.add(b); }  return collection; } catch (SQLException ex) { throw new DAOException(ex);  } finally { close(st); } }
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
References ,[object Object]

More Related Content

What's hot

WSDL-Design-and-Generation-in-EASparx
WSDL-Design-and-Generation-in-EASparxWSDL-Design-and-Generation-in-EASparx
WSDL-Design-and-Generation-in-EASparxFrank Ning
 
A introduction to oracle data integrator
A introduction to oracle data integratorA introduction to oracle data integrator
A introduction to oracle data integratorchkamal
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05Niit Care
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#Michael Heron
 
Ado.net session10
Ado.net session10Ado.net session10
Ado.net session10Niit Care
 
Ado.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksAdo.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksLuis Goldster
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
Jdbc 4.0 New Features And Enhancements
Jdbc 4.0 New Features And EnhancementsJdbc 4.0 New Features And Enhancements
Jdbc 4.0 New Features And Enhancementsscacharya
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Vidyasagar Mundroy
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Mubarak Hussain
 

What's hot (20)

WSDL-Design-and-Generation-in-EASparx
WSDL-Design-and-Generation-in-EASparxWSDL-Design-and-Generation-in-EASparx
WSDL-Design-and-Generation-in-EASparx
 
A introduction to oracle data integrator
A introduction to oracle data integratorA introduction to oracle data integrator
A introduction to oracle data integrator
 
Ado.net session05
Ado.net session05Ado.net session05
Ado.net session05
 
Module02
Module02Module02
Module02
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
 
Ado.net session10
Ado.net session10Ado.net session10
Ado.net session10
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Physical Design and Development
Physical Design and DevelopmentPhysical Design and Development
Physical Design and Development
 
Ado.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksAdo.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworks
 
Sql
SqlSql
Sql
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Physical Design and Development
Physical Design and DevelopmentPhysical Design and Development
Physical Design and Development
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Jdbc 4.0 New Features And Enhancements
Jdbc 4.0 New Features And EnhancementsJdbc 4.0 New Features And Enhancements
Jdbc 4.0 New Features And Enhancements
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
 
Schema webinar
Schema webinarSchema webinar
Schema webinar
 

Viewers also liked

Work with my_sql_-_database_in_java
Work with my_sql_-_database_in_javaWork with my_sql_-_database_in_java
Work with my_sql_-_database_in_javaAsya Dudnik
 
Data Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБДData Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБДCUSTIS
 
Lecture data base programming part2
Lecture data base programming part2Lecture data base programming part2
Lecture data base programming part2ganzorigb
 
Lecture data base programming part1
Lecture data base programming part1Lecture data base programming part1
Lecture data base programming part1ganzorigb
 
Коллекции в Java
Коллекции в JavaКоллекции в Java
Коллекции в Javametaform
 
Работа с БД в Java
Работа с БД в JavaРабота с БД в Java
Работа с БД в Javametaform
 
Database Connectivity with JDBC
Database Connectivity with JDBCDatabase Connectivity with JDBC
Database Connectivity with JDBCDudy Ali
 
Lecture data base programming part3
Lecture data base programming part3Lecture data base programming part3
Lecture data base programming part3ganzorigb
 
PostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все сокиPostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все сокиVladimir Sitnikov
 
Lecture03 p1
Lecture03 p1Lecture03 p1
Lecture03 p1aa11bb11
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course JavaEE Trainers
 
Web application using JSP
Web application using JSPWeb application using JSP
Web application using JSPKaml Sah
 
1 intro of data structure course
1  intro of data structure course1  intro of data structure course
1 intro of data structure courseMahmoud Alfarra
 

Viewers also liked (20)

Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Jdbc in java
Jdbc in javaJdbc in java
Jdbc in java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Work with my_sql_-_database_in_java
Work with my_sql_-_database_in_javaWork with my_sql_-_database_in_java
Work with my_sql_-_database_in_java
 
Data Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБДData Access Layer как страховка на случай миграции СУБД
Data Access Layer как страховка на случай миграции СУБД
 
Lecture data base programming part2
Lecture data base programming part2Lecture data base programming part2
Lecture data base programming part2
 
Lecture data base programming part1
Lecture data base programming part1Lecture data base programming part1
Lecture data base programming part1
 
Коллекции в Java
Коллекции в JavaКоллекции в Java
Коллекции в Java
 
Работа с БД в Java
Работа с БД в JavaРабота с БД в Java
Работа с БД в Java
 
Database Connectivity with JDBC
Database Connectivity with JDBCDatabase Connectivity with JDBC
Database Connectivity with JDBC
 
Lecture data base programming part3
Lecture data base programming part3Lecture data base programming part3
Lecture data base programming part3
 
PostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все сокиPostgreSQL и JDBC: выжимаем все соки
PostgreSQL и JDBC: выжимаем все соки
 
Lecture03 p1
Lecture03 p1Lecture03 p1
Lecture03 p1
 
Unit testing
Unit testingUnit testing
Unit testing
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
Software quality assurance
Software quality assuranceSoftware quality assurance
Software quality assurance
 
Web application using JSP
Web application using JSPWeb application using JSP
Web application using JSP
 
jdbc
jdbcjdbc
jdbc
 
Jsp
JspJsp
Jsp
 
1 intro of data structure course
1  intro of data structure course1  intro of data structure course
1 intro of data structure course
 

Similar to Jdbc Dao it-slideshares.blogspot.com

Data Access Tech Ed India
Data Access   Tech Ed IndiaData Access   Tech Ed India
Data Access Tech Ed Indiarsnarayanan
 
Dao pattern
Dao patternDao pattern
Dao patternciriako
 
01 Persistence And Orm
01 Persistence And Orm01 Persistence And Orm
01 Persistence And OrmRanjan Kumar
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldevllangit
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersllangit
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developersllangit
 
Modern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas JellemaModern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas JellemaLucas Jellema
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersukdpe
 
Overview of atg framework
Overview of atg frameworkOverview of atg framework
Overview of atg frameworkYousuf Roushan
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Servicesukdpe
 
Introducing SOA and Oracle SOA Suite 11g for Database Professionals
Introducing SOA and Oracle SOA Suite 11g for Database ProfessionalsIntroducing SOA and Oracle SOA Suite 11g for Database Professionals
Introducing SOA and Oracle SOA Suite 11g for Database ProfessionalsLucas Jellema
 
Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator projectAmit Sharma
 
What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?ukdpe
 
SQL Server 2008 Overview
SQL Server 2008 OverviewSQL Server 2008 Overview
SQL Server 2008 OverviewEric Nelson
 
RDBMS to NoSQL: Practical Advice from Successful Migrations
RDBMS to NoSQL: Practical Advice from Successful MigrationsRDBMS to NoSQL: Practical Advice from Successful Migrations
RDBMS to NoSQL: Practical Advice from Successful MigrationsScyllaDB
 
vFabric SQLFire for high performance data
vFabric SQLFire for high performance datavFabric SQLFire for high performance data
vFabric SQLFire for high performance dataVMware vFabric
 

Similar to Jdbc Dao it-slideshares.blogspot.com (20)

Data Access Tech Ed India
Data Access   Tech Ed IndiaData Access   Tech Ed India
Data Access Tech Ed India
 
Dao pattern
Dao patternDao pattern
Dao pattern
 
01 Persistence And Orm
01 Persistence And Orm01 Persistence And Orm
01 Persistence And Orm
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldev
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developers
 
Modern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas JellemaModern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas Jellema
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
Overview of atg framework
Overview of atg frameworkOverview of atg framework
Overview of atg framework
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
Intro
IntroIntro
Intro
 
Introduction to Oracle
Introduction to OracleIntroduction to Oracle
Introduction to Oracle
 
Introduction to Oracle
Introduction to OracleIntroduction to Oracle
Introduction to Oracle
 
Introducing SOA and Oracle SOA Suite 11g for Database Professionals
Introducing SOA and Oracle SOA Suite 11g for Database ProfessionalsIntroducing SOA and Oracle SOA Suite 11g for Database Professionals
Introducing SOA and Oracle SOA Suite 11g for Database Professionals
 
7 data management design
7 data management design7 data management design
7 data management design
 
Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator project
 
What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?
 
SQL Server 2008 Overview
SQL Server 2008 OverviewSQL Server 2008 Overview
SQL Server 2008 Overview
 
RDBMS to NoSQL: Practical Advice from Successful Migrations
RDBMS to NoSQL: Practical Advice from Successful MigrationsRDBMS to NoSQL: Practical Advice from Successful Migrations
RDBMS to NoSQL: Practical Advice from Successful Migrations
 
vFabric SQLFire for high performance data
vFabric SQLFire for high performance datavFabric SQLFire for high performance data
vFabric SQLFire for high performance data
 

More from phanleson

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Sparkphanleson
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewallsphanleson
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hackingphanleson
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocolsphanleson
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacksphanleson
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applicationsphanleson
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designphanleson
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operationsphanleson
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBasephanleson
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibphanleson
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streamingphanleson
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLphanleson
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Clusterphanleson
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programmingphanleson
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Dataphanleson
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairsphanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Sparkphanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagiaphanleson
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLphanleson
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Webphanleson
 

More from phanleson (20)

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewalls
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hacking
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocols
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table design
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operations
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBase
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlib
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQL
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Cluster
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programming
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Data
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairs
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XML
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Web
 

Jdbc Dao it-slideshares.blogspot.com

  • 1. JDBC and Data Access Objects
  • 2.
  • 3.
  • 4. Data Access Object (DAO) Pattern
  • 5.
  • 6.
  • 7.
  • 9.
  • 10.
  • 12.
  • 13. DAO Interface package ejava.examples.dao; import java.util.Collection; import ejava.examples.dao.domain.Book ; public interface BookDAO { Book create(Book book) throws DAOException ; Book update(Book book) throws DAOException; Book get(long id) throws DAOException; boolean remove(Book book) throws DAOException; Collection<Book> findAll(long start, long count) throws DAOException; }
  • 14. DAO Implementation package ejava.examples.dao.jdbc; ... import ejava.examples.dao.BookDAO; import ejava.examples.dao.DAOException; import ejava.examples.dao.domain.Book; public class JDBCBookDAO extends JDBCDAOBase implements BookDAO { public Book create(Book book) throws DAOException { ... public Book update(Book book) throws DAOException { ... public Book get(long id) throws DAOException { ... public boolean remove(Book book) throws DAOException { ... public Collection<Book> findAll(int start, int count) throws DAOException { ... }
  • 15. Wrapped Exceptions package ejava.examples.dao; public class DAOException extends Exception { private static final long serialVersionUID = 1L; public DAOException() {} public DAOException(String message) { super(message); } public DAOException(String message, Throwable rootCause) { super(message, rootCause); } public DAOException(Throwable rootCause) { super(rootCause); } } try { ... } catch (<T> ex) { throw new DAOException(“troubles”, ex); } * be careful that Resource Level Exception is not propogated all the way back to remote client. May cause ClassNotFoundExceptions
  • 16. Relating Business Objects to Data Transfer Objects (DTOs)
  • 17.
  • 18.
  • 19.
  • 20.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26. Image Table IMAGE_ID IMAGE_TYPE FILENAME URL 1 gif image1 http://host/dir/image1 2 gif image2 ftp://host/dir/image2
  • 27. Image Decoder Table IMAGE_TYPE DECODER_PROGRAM LIC_START LIC_END gif c:ifdecoder 12/01/1998 12/01/1999 jpg d:oolspgdecoder 06/01/1999 12/01/2010
  • 28. Tables and Keys Primary Keys Foreign Key DECODER DECODER IMAGE IMAGE_ID IMAGE_TYPE FILENAME URL 1 gif Image1 … ... IMAGE_TYPE DECODER_PROGRAM gif c:ifdecoder … ...
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 53.
  • 54.
  • 55.  
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62. DriverManager package java.sql; public class DriverManager { public static synchronized Connection getConnection( String url, String username, String password) {... public static synchronized Connection getConnection( String url, Properties props) { ... public static synchronized Connection getConnection( String url) public static synchronized Driver getDriver( String url) { ... public static synchronized void registerDriver( java.sql.Driver driver) { ... public static synchronized void deregisterDriver( Driver driver) { ... public static synchronized java.util.Enumeration<Driver> getDrivers() { ... public static void setLoginTimeout( int seconds) { ... public static java.io.PrintWriter getLogWriter() { ... public static void setLogWriter( java.io.PrintWriter out) { ... public static void println( String message) { ...
  • 63. Driver package java.sql; public interface Driver { Connection connect(String url, java.util.Properties info) throws SQLException; boolean acceptsURL(String url) throws SQLException; DriverPropertyInfo[] getPropertyInfo( String url, java.util.Properties info) throws SQLException; int getMinorVersion(); boolean jdbcCompliant(); }
  • 64. Connection package java.sql; public interface Connection { Statement createStatement() throws SQLException; PreparedStatement prepareStatement( String sql)throws SQLException; CallableStatement prepareCall( String sql) throws SQLException; PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)throws SQLException; CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency) throws SQLException; Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException; PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException; CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException; PreparedStatement prepareStatement( String sql, int autoGeneratedKeys) throws SQLException; PreparedStatement prepareStatement( String sql, int columnIndexes[]) throws SQLException; PreparedStatement prepareStatement( String sql, String columnNames[])throws SQLException; ...
  • 65. Connection package java.sql; public interface Connection { ... void setAutoCommit( boolean autoCommit) throws SQLException; boolean getAutoCommit() throws SQLException; void commit() throws SQLException; void rollback() throws SQLException; void close() throws SQLException; boolean isClosed() throws SQLException; void setTransactionIsolation(int level) throws SQLException; int getTransactionIsolation() throws SQLException; SQLWarning getWarnings() throws SQLException; void clearWarnings() throws SQLException; Savepoint setSavepoint() throws SQLException; Savepoint setSavepoint(String name) throws SQLException; void rollback(Savepoint savepoint) throws SQLException; void releaseSavepoint(Savepoint savepoint) throws SQLException; ...
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73. Statement package java.sql; public interface Statement { ... ResultSet executeQuery(String sql) throws SQLException; int executeUpdate(String sql) throws SQLException; SQLWarning getWarnings() throws SQLException; void clearWarnings() throws SQLException; boolean execute(String sql) throws SQLException; ResultSet getResultSet() throws SQLException; int getUpdateCount() throws SQLException; boolean getMoreResults() throws SQLException; int getResultSetType() throws SQLException; void addBatch( String sql ) throws SQLException; void clearBatch() throws SQLException; int[] executeBatch() throws SQLException; boolean getMoreResults(int current) throws SQLException; ResultSet getGeneratedKeys() throws SQLException; int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException; int executeUpdate(String sql, int columnIndexes[]) throws SQLException; int executeUpdate(String sql, String columnNames[]) throws SQLException; boolean execute(String sql, int autoGeneratedKeys) throws SQLException; boolean execute(String sql, int columnIndexes[]) throws SQLException; boolean execute(String sql, String columnNames[]) throws SQLException; ...
  • 74. Statement package java.sql; public interface Statement { ... int getMaxFieldSize() throws SQLException; void setMaxFieldSize(int max) throws SQLException; int getMaxRows() throws SQLException; void setMaxRows(int max) throws SQLException; void setEscapeProcessing(boolean enable) throws SQLException; int getQueryTimeout() throws SQLException; void setQueryTimeout(int seconds) throws SQLException; void cancel() throws SQLException; void setCursorName(String name) throws SQLException; boolean execute(String sql) throws SQLException; void setFetchDirection(int direction) throws SQLException; int getFetchDirection() throws SQLException; void setFetchSize(int rows) throws SQLException; int getFetchSize() throws SQLException; int getResultSetConcurrency() throws SQLException; void addBatch( String sql ) throws SQLException; void clearBatch() throws SQLException; Connection getConnection() throws SQLException; ResultSet getGeneratedKeys() throws SQLException; int getResultSetHoldability() throws SQLException; ...
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 86.
  • 88. Schema create sequence DAO_BOOK_SEQ as int start with 100 increment by 1; create table DAO_BOOK_UID ( ID bigint ); insert into DAO_BOOK_UID (ID) VALUES ( NEXT VALUE FOR DAO_BOOK_SEQ ); create table DAO_BOOK ( ID bigint not null, VERSION bigint not null, TITLE varchar(64), AUTHOR varchar(64), DESCRIPTION varchar(2000), PAGES int, CONSTRAINT dao_BookPK PRIMARY KEY(ID) );
  • 89. Example DAO Test Client Connection connection; BookDAO dao; protected void setUp() throws Exception { connection = getConnection(); connection.setAutoCommit(false); JDBCBookDAO.setConnection(connection); dao = new JDBCBookDAO(); } public void testCreate() throws Exception { Book book = new Book(nextId()); book.setTitle(&quot;a&quot;); book.setAuthor(&quot;b&quot;); book.setDescription(&quot;testCreate&quot;); book.setPages(20); try { Book book2 = dao.create(book); connection.commit(); assertNotNull(book2); } catch (Exception ex) { connection.rollback(); fail(&quot;&quot; + ex); } }
  • 90. Connection Sharing using ThreadLocal package ejava.examples.dao.jdbc; import java.sql.*; public class JDBCDAOBase { static ThreadLocal<Connection> connection = new ThreadLocal<Connection>(); public static void setConnection(Connection conn) { connection.set(conn); } protected Connection getConnection() throws IllegalStateException { Connection conn = connection.get(); if (conn == null) { throw new IllegalStateException( &quot;Connection has not been set&quot;); } return conn; }
  • 91. Resource Helpers protected static void closeConnection() throws SQLException { Connection conn = connection.get(); if (conn != null) { connection.set(null); conn.close(); } } protected void close(Statement st) { try { st.close();} catch (Throwable ignored) {} } protected void close(ResultSet rs) { try { rs.close();} catch (Throwable ignored) {} }
  • 92. Inserting Object (and calling a private setter) public Book create(Book book) throws DAOException { long id = (book.getId() == 0) ? getNextId() : book.getId(); PreparedStatement st = null; try { st = getConnection().prepareStatement( &quot;INSERT INTO &quot; + TABLE_NAME + &quot; &quot; + &quot;(ID, VERSION, TITLE, AUTHOR, DESCRIPTION, PAGES) &quot; + &quot;VALUES(?, ?, ?, ?, ?, ?)&quot;); st.setLong(1, id); st.setLong(2, 0); st.setString(3, book.getTitle()); st.setString(4, book.getAuthor()); st.setString(5, book.getDescription()); st.setInt(6, book.getPages()); if (st.executeUpdate() != 1) { throw new DAOException(&quot;unable to insert Book&quot;); } book.setVersion(0); if (book.getId()==0) { //use reflection to get private setId method of Book class Method setId = Book.class.getDeclaredMethod( &quot;setId&quot;, new Class[] { int.class }); setId.setAccessible(true); setId.invoke(book, new Object[] { id }); } return book; } catch (Exception ex) { throw new DAOException(ex); } finally { close(st); } }
  • 93. Generating an ID public int getNextId() throws DAOException { Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); st.executeUpdate(&quot;UPDATE DAO_BOOK_UID &quot; + &quot;SET ID=NEXT VALUE FOR DAO_BOOK_SEQ”); rs = st.executeQuery(&quot;SELECT ID FROM DAO_BOOK_UID”); rs.next(); return rs.getInt(1); } catch (SQLException ex) { throw new DAOException(ex); } finally { close(rs); close(st); } }
  • 94. Updating Database public Book update(Book book) throws DAOException { if (book.getId() == 0) { throw new DAOException(&quot;Book does not have primary key&quot;); } PreparedStatement st = null; try { long version = getVersion(book.getId()); st = getConnection().prepareStatement(&quot;UPDATE &quot; + TABLE_NAME + &quot; &quot; + &quot;SET VERSION=?, TITLE=?, AUTHOR=?, DESCRIPTION=?, PAGES=? &quot; + &quot;WHERE ID=?&quot;); st.setLong(1, ++version); st.setString(2, book.getTitle()); st.setString(3, book.getAuthor()); st.setString(4, book.getDescription()); st.setInt(5, book.getPages()); st.setLong(6, book.getId()); int count = st.executeUpdate(); if (count == 0) { throw new DAOException(&quot;Object not found:&quot; + book.getId()); } book.setVersion(version); return book; } catch (SQLException ex) { throw new DAOException(ex); } finally { close(st); } }
  • 95. Getting Version (Helper) protected long getVersion(long id) throws SQLException, DAOException { long version = 0; Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); rs = st.executeQuery(&quot;SELECT VERSION FROM &quot; + TABLE_NAME + &quot; WHERE ID=&quot; + id); if (!rs.next()) { throw new DAOException(&quot;Object not found&quot;); } version = rs.getLong(1); } finally { close(rs); close(st); } return version; }
  • 96. Getting Object By ID public Book get(long id) throws DAOException { Book book = null; Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); rs = st.executeQuery( &quot;SELECT VERSION, AUTHOR, TITLE, DESCRIPTION, PAGES &quot; + &quot;FROM &quot; + TABLE_NAME + &quot; &quot; + &quot;WHERE ID=&quot; + id); if (!rs.next()) { throw new DAOException(&quot;Object not found&quot;); } book = new Book(id); book.setVersion(rs.getLong(1)); book.setAuthor(rs.getString(2)); book.setTitle(rs.getString(3)); book.setDescription(rs.getString(4)); book.setPages(rs.getInt(5)); return book; } catch (SQLException ex) { throw new DAOException(ex); } finally { close(rs); close(st); } }
  • 97. Removing Object public boolean remove(Book book) throws DAOException { Statement st = null; try { st = getConnection().createStatement(); int count = st.executeUpdate(&quot;DELETE FROM &quot; + TABLE_NAME + &quot; WHERE ID=&quot; + book.getId()); return count == 1; } catch (SQLException ex) { throw new DAOException(ex); } finally { close(st); } }
  • 98. Finding Objects public Collection<Book> findAll(int start, int count) throws DAOException { Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = st.executeQuery(&quot;SELECT * FROM &quot; + TABLE_NAME); Collection<Book> collection = new ArrayList<Book>(); rs.absolute(start); int i=0; while (rs.next() && i++<count) { Book b = new Book(rs.getLong(&quot;ID&quot;)); b.setAuthor(rs.getString(&quot;AUTHOR&quot;)); b.setDescription(rs.getString(&quot;DESCRIPTION&quot;)); b.setPages(rs.getInt(&quot;PAGES&quot;)); b.setTitle(rs.getString(&quot;TITLE&quot;)); b.setVersion(rs.getLong(&quot;VERSION&quot;)); collection.add(b); } return collection; } catch (SQLException ex) { throw new DAOException(ex); } finally { close(st); } }
  • 99.
  • 100.