SlideShare a Scribd company logo
Java course - IAG0040




             JDBC & Logging




Anton Keks                            2011
JDBC
 â—Ź
     Java DataBase Connectivity
     –   The API for DB access from Java
     –   Oriented towards relational databases
     –   java.sql package
     –   JDBC is DB vendor neutral
 â—Ź   Versions
     –   Exists since Java 1.1
     –   Java 1.4 & 1.5 ships with JDBC 3
     –   Java 1.6 introduced JDBC 4
Java course - IAG0040                            Lecture 13
Anton Keks                                           Slide 2
JDBC drivers
 â—Ź
     java.sql.Driver - the driver side of the JDBC
     layer is the part that interfaces with the
     actual database, and therefore is generally
     written by database vendors
 â—Ź
     Most developers only need to know how to
     install and use drivers. The JDBC Driver API
     defines a set of interfaces which have to be
     implemented by a vendor


Java course - IAG0040                          Lecture 13
Anton Keks                                         Slide 3
JDBC driver types
 â—Ź
     Type 1 use a bridge technology to connect a Java client to
     ODBC system. The JDBC-ODBC bridge from Sun is one example
     of a Type 1 driver
 â—Ź   Type 2 use native code library to access a database, wrapping
     a thin layer of Java around the native library, e.g. Oracle OCI
     driver
 â—Ź   Type 3 drivers define a generic network protocol that
     interfaces with a piece of custom middleware. The
     middleware component might use any other type of driver to
     provide the actual database access.
 â—Ź   Type 4 drivers are implemented entirely in Java. They
     understand database-specific networking protocols and can
     access the database directly without any additional software.
Java course - IAG0040                                        Lecture 13
Anton Keks                                                       Slide 4
JDBC driver summary

     Type 1              ODBC
   ODBC bridge           diver


     Type 2             Native API
    Native API

      Type 3                         Middleware
                                                  DB
      Network                          server


      Type 4
     Pure Java


Java course - IAG0040                             Lecture 13
Anton Keks                                            Slide 5
JDBC API basics
                        ResultSet


           Statement            PreparedStatement     CallableStatement



                                      Connection
    Application

                                    DriverManager

                                                       Oracle, MySQL,
                                    Concrete Driver     PostgreSQL,
                                                        HSQLDB, etc


                                     Concrete DB


Java course - IAG0040                                               Lecture 13
Anton Keks                                                              Slide 6
JDBC basic usage
 â—Ź
     Load the driver (was needed before JDBC 4)
     –   Class.forName(“driverClassName”);
     –   System property -Djdbc.drivers=driverClassName
 â—Ź
     Use DriverManager to create connection
     –   DriverManager.getConnection(url, user, password);
 â—Ź
     Create statement for execution
     –   connection.createStatement();
 â—Ź
     Execute the query and get a ResultSet
     –   statement.executeQuery(sql);
 â—Ź   Iterate over ResultSet: rs.next() and rs.getXXX()
 â—Ź   Free resources with close() methods
Java course - IAG0040                                     Lecture 13
Anton Keks                                                    Slide 7
Connection
 â—Ź
     java.sql.Connection
 â—Ź   Represents an open connection to the DB
 â—Ź   Obtained via a DriverManager
     –   DriverManager.getConnection(url, user, password)
 â—Ź
     URL starts with jdbc:
     –   The exact format depends on the vendor
     –   jdbc:mysql://server:port/dbname
     –   jdbc:hsqldb:mem:dbname
     –   jdbc:oracle:thin:@server:port:sid
Java course - IAG0040                              Lecture 13
Anton Keks                                             Slide 8
Statement & PreparedStatement
 â—Ź
     java.sql.Statement
      –   for execution of simple statements without
          parameters
      –   s = conn.createStatement();
          s.execute(“CREATE TABLE ..”);

 â—Ź
     java.sql.PreparedStatement
      –   for execution of parametrized statements via
          'parameter binding'
      –   s = conn.prepareStatement(“SELECT .. WHERE ID = ?”)
          s.setInt(1, value); ResultSet rs = s.executeQuery();
      –   allows for reuse of pre-compiled statements
Java course - IAG0040                                    Lecture 13
Anton Keks                                                   Slide 9
ResultSet
 â—Ź
     java.sql.ResultSet
     –   represents result of a SQL query, containing
         multiple rows, similar to an Iterator
     –   ResultSet rs = s.executeQuery(“SELECT ...”);
         while (rs.next()) {
            rs.getString(1); or rs.getString(“COLUMN”);
         }
         rs.close();
     –   cursor movement by default is
         ResultSet.TYPE_FORWARD_ONLY
          â—Ź   Some drivers may support bidirectional
              movement
Java course - IAG0040                                     Lecture 13
Anton Keks                                                  Slide 10
CallableStatement
 â—Ź
     java.sql.CallableStatement
     –   extends PreparedStatement
     –   intended for calling stored procedures in the DB
     –   allows reading of OUT parameters instead of
         getting a ResultSet
     –   s = conn.prepareCall(“{call SOME_PROC(?, ?, ?)}”);
         s.setString(1, “some value”);
         s.registerOutParameter(2, Types.VARCHAR);
         s.registerOutParameter(3, Types.NUMERIC);

         s.execute();
         String result1 = s.getString(2);
         int result2 = s.getInt(3);

Java course - IAG0040                                   Lecture 13
Anton Keks                                                Slide 11
Resourse Management
 â—Ź
     All DB objects have the close() method
     –   higher-level DB objects automatically close the
         lower-level ones
     –   conn.close() will close all underlying statements
 â—Ź   Don't forget proper closing
     –   same pattern applies as with java.io
     –   it is a good idea to put close() into a finally block!



Java course - IAG0040                                    Lecture 13
Anton Keks                                                 Slide 12
Metadata
 â—Ź
     DatabaseMetaData, ResultSetMetaData,
     ParameterMetaData
     –   Metadata provides additional information about
         the respective DB objects
     –   Can be used for discovering of DB structure and
         other 'advanced' or non-standard code
     –   DatabaseMetaData metadata = conn.getMetaData();
         String name = metadata.getDatabaseProductName();
     –   ResultSet rs = s.executeQuery(“SELECT ...”);
         ResultSetMetaData metadata = rs.getMetaData();
         int columns = metadata.getColumnCount();


Java course - IAG0040                                     Lecture 13
Anton Keks                                                  Slide 13
Transactions
 â—Ź
     Connection auto-commit is ON by default
     –   Use conn.setAutoCommit(false) to control
         transactions manually
 â—Ź
     Transaction control
     –   connection.commit() persists the changes
     –   connection.rollback() cancels the changes
     –   connection.setSavepoint() bookmarks transactions
     –   exact behaviour depends on the concrete DB


Java course - IAG0040                                 Lecture 13
Anton Keks                                              Slide 14
DataSource
 â—Ź
     java.sql.DataSource
     –   a bean-style alternative to DriverManager
     –   implemented by a DB vendor
 â—Ź   Is usually initialized in a vendor-specific way in
     the application container
     –   provides getConnection() method
 â—Ź   Spring Framework and Commons-DBCP have
     useful implementations, e.g. for connection
     pooling
Java course - IAG0040                                Lecture 13
Anton Keks                                             Slide 15
Data Access Patterns
 â—Ź
     Define where to put the JDBC-related code in
     an application
 â—Ź   In general:
     –   Isolate and encapsulate JDBC code
     –   Very few classes should know where the data
         comes from
     –   Pass data around as domain objects, not ResultSets
         or a mix of Strings or primitive types



Java course - IAG0040                               Lecture 13
Anton Keks                                            Slide 16
Active Domain Object Pattern
 â—Ź
     aka ActiveRecord
 â—Ź   Wraps a row in a table or view, encapsulates
     DB access, and adds domain logic
     –   JDBC only used internally, not visible from the
         outside
     –   Person person = Person.create();
         person.setName(“John Doe”);
         person.save();
     –   Person person = Person.load(“John Doe”);



Java course - IAG0040                                 Lecture 13
Anton Keks                                              Slide 17
Data Accessor Pattern
 â—Ź
     aka Data Access Object (DAO)
 â—Ź   Encapsulates physical data access in a single
     component, exposing logical operations
     –   Application code maintains knowledge about the
         underlying data model, but is decoupled from the
         data access possibilities
     –   Domain objects know nothing about the DB
     –   PersonAccessor dao = new JDBCPersonAccessor();
         Person person = dao.loadPerson(“John Doe”);
         person.setName(“John Smith”);
         dao.save(person);

Java course - IAG0040                               Lecture 13
Anton Keks                                            Slide 18
Testing
 â—Ź
     Clear separation of DB access logic from
     business logic makes testing and maintenance
     a lot easier
 â—Ź
     All JDBC interfaces can be easily mocked
     –   Connection conn = createMock(Connection.class);
 â—Ź
     Sometimes it is wise to test the full-cycle
     –   Use in-memory database, e.g. HSQLDB
     –   Initialize the data there and substitute DB
         connection with the fake in-memory one
     –   DBUnit can help with that
Java course - IAG0040                                  Lecture 13
Anton Keks                                               Slide 19
Logging
 â—Ź   When writing more complex applications, you need logging in
     your code
      –   you don't want to show low-level crash info to end-users
      –   debugging of bugs on production is usually not possible
 â—Ź   There are many possibilities to implement logging:
      –   System.out / System.err or other java.io classes – usually
          primitive and not flexible solution
      –   java.util.logging, e.g. Logger class – logging API included in Java
          since 1.4, configurable and extensible
      –   Log4J – very popular de-facto standard framework, very
          powerful, has a very good API
      –   Jakarta commons-logging – the facade for different logging APIs
Java course - IAG0040                                                Lecture 13
Anton Keks                                                             Slide 20
java.util.logging
 â—Ź   Logger LOG = Logger.getLogger(this.getClass().getName());
      –   Loggers have hierarchical structure ('.' separated), it is a good idea to use
          full class name as a logger name
      –   Logger often used as a static member (for convenience)
 â—Ź   Loggers can be used for logging information with various levels
      –   SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST
      –   LOG.severe(“We have a problem!”);
      –   LOG.log(Level.SEVERE, “We have a problem”, exception);
 â—Ź   java.util.logging is configurable
      –   by default it uses $JAVA_HOME/jre/lib/logging.properties
      –   specific file is specified with sys. property java.util.logging.config.file


Java course - IAG0040                                                           Lecture 13
Anton Keks                                                                        Slide 21
java.util.logging (cont)
 â—Ź   Logger is used to produce LogRecords
      –   every LogRecord has a specified logging Level
      –   every Logger may have its own Level assigned
      –   or they inherit Level from their parent
 â—Ź   LogRecords are passed to one or more Handlers
      –   e.g. ConsoleHandler, FileHandler, MemoryHandler, SocketHandler, etc
      –   every handler writes logs greater or equal to their assigned Level
 â—Ź   Formatters are used for formatting of LogRecords
      –   SimpleFormatter or XMLFormatter
 â—Ź   a LogRecord is written only if its Level is greater than of its Logger's and if
     there is a Handler configured to write at this Level
 â—Ź   Filters may be used for more fine-grained control of what should be logged

Java course - IAG0040                                                        Lecture 13
Anton Keks                                                                     Slide 22
Log4J (org.apache.log4j)
 â—Ź   Logger LOG = Logger.getLogger(this.getClass());
      –   Loggers have hierarchical structure ('.' separated), same as util.logging
 â—Ź   Loggers can be used for logging information with various levels
      –   FATAL, ERROR, WARN, INFO, DEBUG are default levels
      –   LOG.error(“We have a problem!”, exception);
 â—Ź   Log4J is fully configurable with external files
      –   there is no default configuration
      –   it automatically looks for log4j.xml or log4j.properties in classpath
      –   can be overriden with log4j.configuration system property
      –   every named logger can have its own configuration
      –   different appenders can be used for writing the actual data

Java course - IAG0040                                                      Lecture 13
Anton Keks                                                                   Slide 23

More Related Content

PDF
Java Course 12: XML & XSL, Web & Servlets
PDF
Java Course 15: Ant, Scripting, Spring, Hibernate
PDF
Java Course 1: Introduction
PDF
Java Course 7: Text processing, Charsets & Encodings
PDF
Java Course 14: Beans, Applets, GUI
PDF
Java Course 2: Basics
PDF
Java Course 6: Introduction to Agile
PDF
Java Course 3: OOP
Java Course 12: XML & XSL, Web & Servlets
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 1: Introduction
Java Course 7: Text processing, Charsets & Encodings
Java Course 14: Beans, Applets, GUI
Java Course 2: Basics
Java Course 6: Introduction to Agile
Java Course 3: OOP

What's hot (20)

PDF
Java Course 4: Exceptions & Collections
PDF
Java Course 11: Design Patterns
PPT
Hibernate introduction
PPTX
Core Java introduction | Basics | free course
PPTX
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
PPTX
Core java
PPT
Java New Evolution
PPTX
Core java1
PPSX
Introduction to java
PDF
Core Java
PPT
Java basic
PDF
Core Java Tutorial
PPTX
Java training in delhi
PPTX
Java 9
PPTX
Unit1 introduction to Java
PPTX
What is Java? Presentation On Introduction To Core Java By PSK Technologies
PDF
Introduction to Java
PDF
Java Concurrency Quick Guide
PDF
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
PPT
Java basic introduction
Java Course 4: Exceptions & Collections
Java Course 11: Design Patterns
Hibernate introduction
Core Java introduction | Basics | free course
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Core java
Java New Evolution
Core java1
Introduction to java
Core Java
Java basic
Core Java Tutorial
Java training in delhi
Java 9
Unit1 introduction to Java
What is Java? Presentation On Introduction To Core Java By PSK Technologies
Introduction to Java
Java Concurrency Quick Guide
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java basic introduction
Ad

Similar to Java Course 13: JDBC & Logging (20)

PPS
Java session16
PDF
Jdbc
PPS
Dacj 4 1-a
PDF
PDF
10 J D B C
PDF
Presentation for java data base connectivity
PPT
Chap3 3 12
PDF
Jdbc 1
PDF
Lecture17
PDF
Java Web Programming [3/9] : Servlet Advanced
DOC
Java database programming with jdbc
PDF
Java Web Programming Using Cloud Platform: Module 3
PPS
Jdbc session01
PPTX
Jdbc
PDF
Java Database Connectivity (Advanced programming)
PPT
Jdbc sasidhar
PPTX
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
PPT
JDBC Connectivity Model
PPTX
Core jdbc basics
Java session16
Jdbc
Dacj 4 1-a
10 J D B C
Presentation for java data base connectivity
Chap3 3 12
Jdbc 1
Lecture17
Java Web Programming [3/9] : Servlet Advanced
Java database programming with jdbc
Java Web Programming Using Cloud Platform: Module 3
Jdbc session01
Jdbc
Java Database Connectivity (Advanced programming)
Jdbc sasidhar
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
JDBC Connectivity Model
Core jdbc basics
Ad

More from Anton Keks (10)

PDF
Being a professional software tester
PDF
Java Course 10: Threads and Concurrency
PDF
Java Course 9: Networking and Reflection
PDF
Java Course 8: I/O, Files and Streams
PDF
Java Course 5: Enums, Generics, Assertions
PDF
Choose a pattern for a problem
PDF
Simple Pure Java
PDF
Database Refactoring
PDF
Scrum is not enough - being a successful agile engineer
PDF
Being a Professional Software Developer
Being a professional software tester
Java Course 10: Threads and Concurrency
Java Course 9: Networking and Reflection
Java Course 8: I/O, Files and Streams
Java Course 5: Enums, Generics, Assertions
Choose a pattern for a problem
Simple Pure Java
Database Refactoring
Scrum is not enough - being a successful agile engineer
Being a Professional Software Developer

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
KodekX | Application Modernization Development
 
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
cuic standard and advanced reporting.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Spectral efficient network and resource selection model in 5G networks
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Big Data Technologies - Introduction.pptx
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Approach and Philosophy of On baking technology
MYSQL Presentation for SQL database connectivity
sap open course for s4hana steps from ECC to s4
Dropbox Q2 2025 Financial Results & Investor Presentation
KodekX | Application Modernization Development
 
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
cuic standard and advanced reporting.pdf
Machine learning based COVID-19 study performance prediction
Advanced methodologies resolving dimensionality complications for autism neur...
Spectral efficient network and resource selection model in 5G networks

Java Course 13: JDBC & Logging

  • 1. Java course - IAG0040 JDBC & Logging Anton Keks 2011
  • 2. JDBC â—Ź Java DataBase Connectivity – The API for DB access from Java – Oriented towards relational databases – java.sql package – JDBC is DB vendor neutral â—Ź Versions – Exists since Java 1.1 – Java 1.4 & 1.5 ships with JDBC 3 – Java 1.6 introduced JDBC 4 Java course - IAG0040 Lecture 13 Anton Keks Slide 2
  • 3. JDBC drivers â—Ź java.sql.Driver - the driver side of the JDBC layer is the part that interfaces with the actual database, and therefore is generally written by database vendors â—Ź Most developers only need to know how to install and use drivers. The JDBC Driver API defines a set of interfaces which have to be implemented by a vendor Java course - IAG0040 Lecture 13 Anton Keks Slide 3
  • 4. JDBC driver types â—Ź Type 1 use a bridge technology to connect a Java client to ODBC system. The JDBC-ODBC bridge from Sun is one example of a Type 1 driver â—Ź Type 2 use native code library to access a database, wrapping a thin layer of Java around the native library, e.g. Oracle OCI driver â—Ź Type 3 drivers define a generic network protocol that interfaces with a piece of custom middleware. The middleware component might use any other type of driver to provide the actual database access. â—Ź Type 4 drivers are implemented entirely in Java. They understand database-specific networking protocols and can access the database directly without any additional software. Java course - IAG0040 Lecture 13 Anton Keks Slide 4
  • 5. JDBC driver summary Type 1 ODBC ODBC bridge diver Type 2 Native API Native API Type 3 Middleware DB Network server Type 4 Pure Java Java course - IAG0040 Lecture 13 Anton Keks Slide 5
  • 6. JDBC API basics ResultSet Statement PreparedStatement CallableStatement Connection Application DriverManager Oracle, MySQL, Concrete Driver PostgreSQL, HSQLDB, etc Concrete DB Java course - IAG0040 Lecture 13 Anton Keks Slide 6
  • 7. JDBC basic usage â—Ź Load the driver (was needed before JDBC 4) – Class.forName(“driverClassName”); – System property -Djdbc.drivers=driverClassName â—Ź Use DriverManager to create connection – DriverManager.getConnection(url, user, password); â—Ź Create statement for execution – connection.createStatement(); â—Ź Execute the query and get a ResultSet – statement.executeQuery(sql); â—Ź Iterate over ResultSet: rs.next() and rs.getXXX() â—Ź Free resources with close() methods Java course - IAG0040 Lecture 13 Anton Keks Slide 7
  • 8. Connection â—Ź java.sql.Connection â—Ź Represents an open connection to the DB â—Ź Obtained via a DriverManager – DriverManager.getConnection(url, user, password) â—Ź URL starts with jdbc: – The exact format depends on the vendor – jdbc:mysql://server:port/dbname – jdbc:hsqldb:mem:dbname – jdbc:oracle:thin:@server:port:sid Java course - IAG0040 Lecture 13 Anton Keks Slide 8
  • 9. Statement & PreparedStatement â—Ź java.sql.Statement – for execution of simple statements without parameters – s = conn.createStatement(); s.execute(“CREATE TABLE ..”); â—Ź java.sql.PreparedStatement – for execution of parametrized statements via 'parameter binding' – s = conn.prepareStatement(“SELECT .. WHERE ID = ?”) s.setInt(1, value); ResultSet rs = s.executeQuery(); – allows for reuse of pre-compiled statements Java course - IAG0040 Lecture 13 Anton Keks Slide 9
  • 10. ResultSet â—Ź java.sql.ResultSet – represents result of a SQL query, containing multiple rows, similar to an Iterator – ResultSet rs = s.executeQuery(“SELECT ...”); while (rs.next()) { rs.getString(1); or rs.getString(“COLUMN”); } rs.close(); – cursor movement by default is ResultSet.TYPE_FORWARD_ONLY â—Ź Some drivers may support bidirectional movement Java course - IAG0040 Lecture 13 Anton Keks Slide 10
  • 11. CallableStatement â—Ź java.sql.CallableStatement – extends PreparedStatement – intended for calling stored procedures in the DB – allows reading of OUT parameters instead of getting a ResultSet – s = conn.prepareCall(“{call SOME_PROC(?, ?, ?)}”); s.setString(1, “some value”); s.registerOutParameter(2, Types.VARCHAR); s.registerOutParameter(3, Types.NUMERIC); s.execute(); String result1 = s.getString(2); int result2 = s.getInt(3); Java course - IAG0040 Lecture 13 Anton Keks Slide 11
  • 12. Resourse Management â—Ź All DB objects have the close() method – higher-level DB objects automatically close the lower-level ones – conn.close() will close all underlying statements â—Ź Don't forget proper closing – same pattern applies as with java.io – it is a good idea to put close() into a finally block! Java course - IAG0040 Lecture 13 Anton Keks Slide 12
  • 13. Metadata â—Ź DatabaseMetaData, ResultSetMetaData, ParameterMetaData – Metadata provides additional information about the respective DB objects – Can be used for discovering of DB structure and other 'advanced' or non-standard code – DatabaseMetaData metadata = conn.getMetaData(); String name = metadata.getDatabaseProductName(); – ResultSet rs = s.executeQuery(“SELECT ...”); ResultSetMetaData metadata = rs.getMetaData(); int columns = metadata.getColumnCount(); Java course - IAG0040 Lecture 13 Anton Keks Slide 13
  • 14. Transactions â—Ź Connection auto-commit is ON by default – Use conn.setAutoCommit(false) to control transactions manually â—Ź Transaction control – connection.commit() persists the changes – connection.rollback() cancels the changes – connection.setSavepoint() bookmarks transactions – exact behaviour depends on the concrete DB Java course - IAG0040 Lecture 13 Anton Keks Slide 14
  • 15. DataSource â—Ź java.sql.DataSource – a bean-style alternative to DriverManager – implemented by a DB vendor â—Ź Is usually initialized in a vendor-specific way in the application container – provides getConnection() method â—Ź Spring Framework and Commons-DBCP have useful implementations, e.g. for connection pooling Java course - IAG0040 Lecture 13 Anton Keks Slide 15
  • 16. Data Access Patterns â—Ź Define where to put the JDBC-related code in an application â—Ź In general: – Isolate and encapsulate JDBC code – Very few classes should know where the data comes from – Pass data around as domain objects, not ResultSets or a mix of Strings or primitive types Java course - IAG0040 Lecture 13 Anton Keks Slide 16
  • 17. Active Domain Object Pattern â—Ź aka ActiveRecord â—Ź Wraps a row in a table or view, encapsulates DB access, and adds domain logic – JDBC only used internally, not visible from the outside – Person person = Person.create(); person.setName(“John Doe”); person.save(); – Person person = Person.load(“John Doe”); Java course - IAG0040 Lecture 13 Anton Keks Slide 17
  • 18. Data Accessor Pattern â—Ź aka Data Access Object (DAO) â—Ź Encapsulates physical data access in a single component, exposing logical operations – Application code maintains knowledge about the underlying data model, but is decoupled from the data access possibilities – Domain objects know nothing about the DB – PersonAccessor dao = new JDBCPersonAccessor(); Person person = dao.loadPerson(“John Doe”); person.setName(“John Smith”); dao.save(person); Java course - IAG0040 Lecture 13 Anton Keks Slide 18
  • 19. Testing â—Ź Clear separation of DB access logic from business logic makes testing and maintenance a lot easier â—Ź All JDBC interfaces can be easily mocked – Connection conn = createMock(Connection.class); â—Ź Sometimes it is wise to test the full-cycle – Use in-memory database, e.g. HSQLDB – Initialize the data there and substitute DB connection with the fake in-memory one – DBUnit can help with that Java course - IAG0040 Lecture 13 Anton Keks Slide 19
  • 20. Logging â—Ź When writing more complex applications, you need logging in your code – you don't want to show low-level crash info to end-users – debugging of bugs on production is usually not possible â—Ź There are many possibilities to implement logging: – System.out / System.err or other java.io classes – usually primitive and not flexible solution – java.util.logging, e.g. Logger class – logging API included in Java since 1.4, configurable and extensible – Log4J – very popular de-facto standard framework, very powerful, has a very good API – Jakarta commons-logging – the facade for different logging APIs Java course - IAG0040 Lecture 13 Anton Keks Slide 20
  • 21. java.util.logging â—Ź Logger LOG = Logger.getLogger(this.getClass().getName()); – Loggers have hierarchical structure ('.' separated), it is a good idea to use full class name as a logger name – Logger often used as a static member (for convenience) â—Ź Loggers can be used for logging information with various levels – SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST – LOG.severe(“We have a problem!”); – LOG.log(Level.SEVERE, “We have a problem”, exception); â—Ź java.util.logging is configurable – by default it uses $JAVA_HOME/jre/lib/logging.properties – specific file is specified with sys. property java.util.logging.config.file Java course - IAG0040 Lecture 13 Anton Keks Slide 21
  • 22. java.util.logging (cont) â—Ź Logger is used to produce LogRecords – every LogRecord has a specified logging Level – every Logger may have its own Level assigned – or they inherit Level from their parent â—Ź LogRecords are passed to one or more Handlers – e.g. ConsoleHandler, FileHandler, MemoryHandler, SocketHandler, etc – every handler writes logs greater or equal to their assigned Level â—Ź Formatters are used for formatting of LogRecords – SimpleFormatter or XMLFormatter â—Ź a LogRecord is written only if its Level is greater than of its Logger's and if there is a Handler configured to write at this Level â—Ź Filters may be used for more fine-grained control of what should be logged Java course - IAG0040 Lecture 13 Anton Keks Slide 22
  • 23. Log4J (org.apache.log4j) â—Ź Logger LOG = Logger.getLogger(this.getClass()); – Loggers have hierarchical structure ('.' separated), same as util.logging â—Ź Loggers can be used for logging information with various levels – FATAL, ERROR, WARN, INFO, DEBUG are default levels – LOG.error(“We have a problem!”, exception); â—Ź Log4J is fully configurable with external files – there is no default configuration – it automatically looks for log4j.xml or log4j.properties in classpath – can be overriden with log4j.configuration system property – every named logger can have its own configuration – different appenders can be used for writing the actual data Java course - IAG0040 Lecture 13 Anton Keks Slide 23