Tuesday, November 6, 2007

Ref Objects in JAVA

Retrieving REF Values

An SQL REF(structured type) value can be retrieved as a Ref object by calling
the getRef method of the ResultSet and CallableStatement interfaces. For
example, in CODE EXAMPLE 16-6, the ResultSet rscontains a reference to an
instance of the SQL structured type dog that is stored in the table dogs. The code
retrieves this REF(dog) from the first column of rs.

ResultSet rs = stmt.executeQuery("SELECT oid FROM dogs WHERE " +
"name = rover");
rs.next();
Ref ref = rs.getRef(1);

CODE EXAMPLE 16-6 Retrieving a REF value

An SQL REF value is a pointer; therefore, a Ref object, which is the mapping of a
REF value, is likewise a pointer and does not contain the data of the structured type
instance to which it refers. A Ref object remains valid while the session or
connection on which it is created is open.

Retrieving the Referenced Value

The Ref object returned from the method getRef is a reference to an instance of a
structured type in the underlying data source. The methods getObject() and
getObject(Map map) can be used to retrieve the structured type instance that is
referenced.
CODE EXAMPLE 16-7 shows how a reference to an instance of the
structured type Address can be dereferenced to retrieve the instance of Address.This example would require that a map, mapping Address to its SQL type, had been supplied to the Connection using the method setMap.

Ref ref = rs.getRef(1);
Address addr = (Address)ref.getObject();

CODE EXAMPLE 16-7 Retrieving the structured type instance referenced by a Ref object

Storing Ref Objects

The PreparedStatement.setRef method may be called to pass a Ref object as
an input parameter to a PreparedStatement object.

Storing the Referenced Value

An instance of a structured type retrieved with the method ResultSet.getRef or
CallableStatement.getRef is stored using the Ref.setObject method. In
CODE EXAMPLE 16-8, the table DOGS stores instances of the structured type DOG. The
SELECT statement selects the REF(DOG) that refers to the instance in which the
name is Rover. The referenced instance of the type DOG is retrieved using getValue.
The parameter map describes a mapping from the SQL type DOG to the Java class
Dog, which implements the SQLData interface.

ResultSet rs = stmt.executeQuery("SELECT OID FROM DOGS " +
"WHERE NAME = ’ROVER’");
rs.next();
Ref rover = rs.getRef("OID");
Dog dog = (Dog)rover.getObject(map);
// manipulate instance of Dog
dog.setAge(14);

...
// store updated Dog
rover.setObject((Object)dog);

CODE EXAMPLE 16-8 Retrieving and storing the structured type instance referenced by a Ref object

Metadata

The type REF is defined in the class java.sql.Types. This value is returned by
methods such as DatabaseMetaData.getTypeInfo and
DatabaseMetaData.getColumns when a JDBC driver supports the Ref data
type.

No comments: