Tuesday, November 6, 2007

Type Mapping-Streams of SQL Data:JAVA2

Streams of SQL Data

This section describes the stream interfaces, SQLInput and SQLOutput, which
support customization of the mapping of SQL UDTs to Java data types.

Retrieving Data

In a custom mapping, when data of SQL structured and distinct types are retrieved
from the database, they "arrive" in a stream implementing the SQLInput interface.
The SQLInput interface contains methods for reading individual data values
sequentially from the stream. CODE EXAMPLE 17-2 illustrates how a driver can use an
SQLInput stream to provide values for the fields of an SQLData object. The
SQLData object—the this object in the example—contains three persistent fields:
the String str, the Blob object blob, and the Employee object emp.
SQLInput sqlin;
...

this.str = sqlin.readString();
this.blob = sqlin.readBlob();
this.emp = (Employee)sqlin.readObject();

CODE EXAMPLE 17-2 Retrieving data using the SQLInput interface

The SQLInput.readString method reads a String value from the stream; the
SQLInput.readBlob method reads a Blob value from the stream. By default, the
Blob interface is implemented using an SQL locator, so calling the method
readBlob doesn’t materialize the SQL BLOB contents on the client. The
SQLInput.readObject method retrieves an object reference from the stream. In
the example, the Object returned is narrowed to an Employee object.
There are a number of additional methods defined on the SQLInput interface for
reading each of the types (readLong, readBytes, and so on). The
SQLInput.wasNull method can be called to check whether the last value read was
SQL NULL in the database.

Storing Data

When an instance of a class that implements SQLData is passed to a driver as an
input parameter via the setObject method, the JDBC driver calls the object’s
SQLData.writeSQL method. It also creates an SQLOutput stream to which the
method writeSQL writes the attributes of the custom mapped UDT. The method
writeSQL will typically have been generated by a tool from an SQL type definition.

CODE EXAMPLE 17-3 illustrates the use of the SQLOutput object sqlout.

sqlout.writeString(this.str);
sqlout.writeBlob(this.blob);
sqlout.writeObject(this.emp);

CODE EXAMPLE 17-3 Storing data using the SQLOutput interface

The example shows how the contents of an SQLData object can be written to an
SQLOutput stream. The SQLData object—the this object in the example—contains
three persistent fields: the String str, the Blob object blob, and the Employee
object emp. Each field is written in turn to the SQLOutput stream, sqlout. The
SQLOutput interface contains methods for writing each of the types defined in the
JDBC API.

No comments: