4.2. JDBCJDBC has been around nearly as long as Java itself. The JDBC 1.0 API was released with JDK 1.1. This is the java.sql package. JDBC 2.0 was released with JDK 1.2. It included both the Core package and what was called the Optional Package (javax.sql). The optional package brought with it better enterprise support for database connections, including connection pools and distributed transactions. JDBC 3.0 is the latest release, included with JDK 1.4. If you've written JDBC code since the good old days, you're probably familiar with using the DriverManager to get a database connection, as in Example 4-1. Example 4-1. Example of the JDBC DriverManagerstatic final String DB_DRIVER_CLASS = "com.mysql.jdbc.Driver"; static final String DB_URL = "mysql://localhost:3306/JBossatWorkDB?autoReconnect=true"; Connection connection = null; try { // Load the Driver. Class.forName(DB_DRIVER_CLASS).newInstance( ); // Connect to the database. connection = DriverManager.getConnection(DB_URL); } catch (SQLException se) { ... } catch (...) { ... } While this code certainly works, it has several shortcomings:
One of the main benefits of living in an application server is having the server take care of these sorts of plumbing issues. JBoss, like all other J2EE application servers, deals with the issues listed above on your behalf. However, to facilitate this, we need to slightly change the way you obtain your database connections. Rather than using a java.sql.DriverManager, we need to use a javax.sql.DataSource to allow JBoss to manage the details in Example 4-2. Example 4-2. Example of the JDBC DataSourcestatic final String DATA_SOURCE= "java:comp/env/jdbc/JBossAtWorkDS"; DataSource dataSource = null; Connection conn = null; try { // Load the Driver. dataSource = ServiceLocator.getDataSource(DATA_SOURCE); // Connect to the database. conn = dataSource.getConnection( ); } catch (SQLException se) { ... } catch (ServiceLocatorException sle) { ... } A DataSource provides the following advantages:
OK, we admit it. We pulled a bit of a fast one on you. Using DataSources brings great power to the table, but it also brings along some added complexity. We should look at a few more moving parts in greater detail. |