Database Connectivity in Java SWE 642, Fall 2008 Nick Duan What is JDBC? Overview Types of JDBC Drivers JDBC APIs JDBC Data Types JDBC Connection Pool and Data Sources Object-to-Relational Database Mapping Summary 8/17/2008 Nick Duan 2 1
What is JDBC? A set of APIs for connecting database with Java applications. Part of the Java SE standard JDBC Driver: A run-time component (Java classes) to be loaded into the Java application Java Application JDBC API JVM JDBC Driver Database 8/27/2008 Nick Duan 3 Four Types of JDBC Drivers JDBC-ODBC bridge ODBC wrapped with JDBC APIs Part Java, Part Native Driver Driver implemented using vendor s APIs Gateway Database Access Server Driver implemented as a gateway server between application and database Pure Java Drivers Driver implemented to support vendor-specific database protocol 8/27/2008 4 2
JDBC APIs Java SE contains both java.sql and javax.sql packages. The current JDBC version is 4.0. java.sql.* contains the core JDBC APIs Making connections via DriverManager Creating and sending SQL statements to database Retrieving results from a select query APIs for representing SQL Data Types and user defined data types in SQL Retrieving of database metadata SQL Exceptions Javax.sql.* is the optional package for Java EE Getting connections from DataSource Connection Pooling and Statement pooling Distributed transactions (XAConenction and XADataSource) APIs for handling RowSet 8/27/2008 Nick Duan 5 JDBC Programming Steps 1. Initialize a DB driver or data source 2. Obtain a JDBC connection 3. Create and execute SQL statements 4. Retrieve the results by navigating the ResultSets if executing Select statement 5. Close the JDBCconnection! What happened if you leave the connection open? 8/27/2008 Nick Duan 6 3
JDBC Example Other alternatives for loading driver class are try { available Class.forName( org.hsqldb.jdbcdriver ); Connection con = DriverManager.getConnection ( "jdbc:mydriver:wombat", "mylogin","mypassword"); Statement stmt = con.createstatement(); ResultSet rs = stmt.executequery( "SELECT a, b, c FROM mytable"); while (rs.next()) { Enumeration API for int x = rs.getint("a"); navigating through the String s = rs.getstring("b"); ResultSet float f = rs.getfloat("c"); } } System.out.println( Result as follows: + x +, + s +, + f); stmt.close(); // not necessary if connection Must is closed call this method con.close(); to free up connection } resources catch (Exeption e) { } 8/27/2008 Nick Duan 7 PreparedStatement A SQL statement is precompiled and stored in a PreparedStatement object Support variable substitution Enable executing the SQL statement multiple times try { PreparedStatement pstmt = con.preparestatement ("UPDATE EMPLOYEES SET SALARY =? WHERE ID =?"); pstmt.setbigdecimal(1, 153833.00); pstmt.setint(2, 110592); } catch (SQLException e) { } 8/27/2008 Nick Duan 8 4
Mapping SQL Data Types SQL Types mapped to Java Types SQL Types Java Types SQL Types Java Types CHAR String DATE Java.sql.Date VARCHAR String TIME Java.sql.Time LONGVARCHAR String TIMESTAMP Java.sql.Timestamp TINYINT short INTEGER int JAVAOBJECT Object BIGINT Long BLOB Java.sql.Blob interface REAL Float CLOB Java.sql.Clob interface FLOAT Double ARRAY Java.sql.Array interface DOUBLE Double BIT boolean 8/27/2008 Nick Duan 9 Dealing with ResultSet Retrieving Results: ResultSet rs = statement.exeutequery( select * from student ); while (rs.next()) { // defined in an Enumeration API System.out.println(rs.getString( name ) + } Retrieving Result Metadata ResultSetMetaData metadata = rs.getmetadata(); int cnt = metadata.getcolumncount(); String cname = metadata.getcolumnname(n); int typeconstant = metadata.getcolumntype(n); Performing Selective Update Statement stmt = con.createstatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); 8/27/2008 Nick Duan 10 5
Handling Database Transactions Transaction deals with state-changing SQL statements, i.e. insert, update and delete Transaction demarcations (begin, end) are defined by JDBC connection API Default connection setting for transaction is auto-commit, i.e. each statement execution is a transaction by itself To Turn off auto-commit: connection.setautocommit(false) Manual/explicit Transaction control via commit() and rollback() API 8/27/2008 Nick Duan 11 It s All About Connectivity Connection created via DriverManager representing a physical connection Single connection created at a time What s wrong with this? JDBC Connection Pool A set of homogenous JDBC connections managed in a Pool A set of logical connections that map to a set of physical connections Connection.close() doesn t close the physical connection to database 8/27/2008 Nick Duan 12 6
Connection Pool Management Java Application JDBC APIs JDBC Driver Physical Connections Database Server JVM Logical Connections Connection Pool 8/27/2008 Nick Duan 13 JDBC DataSource API Started in JDBC version 2.0, defined in javax.sql package Works in conjunction with Java Naming and Directory Interface (JNDI) to support enterprise database connectivity Support connection pooling and distributed transactions Connection to be created via the DataSource API Context initctx = new InitialContext(); Context envctx = (Context) initctx.lookup("java:comp/env"); DataSource ds = (DataSource) envctx.lookup("jdbc/employeedb"); Connection conn = ds.getconnection(); // use this connection to access the database... conn.close(); 8/27/2008 Nick Duan 14 7
Configuring JDBC DataSource DataSources are to be registered/configured with the JNDI registry embedded in the application server Java Apps Java Java Apps Java Apps Java Apps Servlets Servlet Container Data Data Source Source JNDI Registry Web Application Server (Tomcat) 8/27/2008 Nick Duan 15 Object-to-Relational Database Mapping A set of Java APIs on top of JDBC so that developers don t have to be concerned with dealing with relational data Enables relational data to be handled as object Map database table to class definition Map database record to object Use JavaBeans naming conventions (i.e. getters and setters) Creational/Factory pattern to create Bean objects OO-to-Relational database framework Sun JDO, http://java.sun.com/jdo/index.jsp Hibernate, http://www.hibernate.org/ Apache ibatis, http://ibatis.apache.org/ Oracle TopLink, http://www.oracle.com/technology/products/ias/toplink/index. html 8/27/2008 Nick Duan 16 8
Summary JDBC provides a set of convenient APIs for accessing relational databases Drivers are to be provided by database vendors Different types of drivers for different applications Five steps database access via JDBC Connection pool to be used for large scale applications, especially web applications Use DataSource in conjunction with JNDI for creating pooled connections 8/27/2008 Nick Duan 17 Quiz What type of database drivers should be use in a Java application if you want to interact with multiple databases at the same time? Configure the use of HyperSonic database in Tomcat to support connection pool Modify the sample database applications to use pooled connections 8/27/2008 Nick Duan 18 9