dagblog.
← Archive

Welcome changes in JDBC 4.0


The upcoming Java 6.0 release brings JDBC 4.0, among other things. What can we look forward to?

Automatic JDBC driver loading. Earlier versions of JDBC required you to load the driver class manually by calling Class.forName(). Java 6.0 supports loading it automatically when the vendor declares the driver class in its JAR manifest (META-INF/services/java.sql.Driver).
Connection management. There’s support for managing shared Statement and Connection objects and for metadata that tells you the state of a Connection.
RowId. A new interface, RowId, has been added. ROWID uniquely identifies the database record returned or modified. It’s a database-specific feature, so some databases don’t support it. You can obtain a RowId while traversing a ResultSet, or set it when working with a PreparedStatement.
SQL queries as method annotations. You’ll be able to write SQL as an annotation and use the new generic type DataSet to represent the returned data. A DataSet (which extends java.util.List) takes a JavaBean representing the returned row as its type parameter. The following example shows how it works.

public class Osoba{
private id;
private jmeno;
private prijmeni;

//gettry a settry
}

public interface SQLDotazy extends BaseQuery {
@Select("select id, jmeno, prijmeni from osoba")
DataSet getOsoby();
}
Connection con = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
SQLDotazy dotazy = con.createQueryObject(SQLDotazy.class);
DataSet rows = dotazy.getOsoby();
for (Osoba osoba: rows) {
System.out.println("Jméno = " + osoba.getJmeno();
...
}

Improved exception handling. Two new classes extend SQLException, namely SQLTransientException and SQLNonTransientException, each with its own hierarchy. SQLTransientException and its subclasses are for transient exceptions such as a timeout. SQLNonTransientException is for non-transient exceptions such as a data integrity violation or invalid SQL syntax. Each exception also has getSQLState (which returns SQLstate according to the SQL 2003 specification) and getNextException() (which retrieves a chained exception), and implements Iterable so it can be used with an enhanced for loop.
API changes. There’s support for BLOBs and CLOBs and for the NCHAR, NVARCHAR, LONGNVARCHAR and NCLOB data types (extended types that respect the National Character Set).

Srini Penchikala describes all these features in more detail in JDBC 4.0 Enhancements in Java SE 6. You’ll need Java 6.0 to try them. SDK 6.0 is expected to include Apache Derby, whose driver also serves as the JDBC 4.0 reference implementation.

Medium version

Related articles

Related CZ Podcast episodes