Tuesday, November 6, 2007

Structured Types in JAVA

Retrieving Structured Types

An SQL structured type value is always retrieved by calling the method
getObject. By default, getObject returns a value of type Struct for a structured
type. For example, the following line of code retrieves a Struct value from the first
column of the current row of the ResultSet object rs.

Struct struct = (Struct)rs.getObject(1);

The Struct interface contains methods for retrieving the attributes of a structured
type as an array of java.lang.Object values. By default, a JDBC driver
materializes the contents of a Struct prior to returning a reference to it to the
application. Also, by default a Struct object is considered valid as long as the Java
application maintains a reference to it.

Storing Structured Types

The PreparedStatement.setObject method may be called to pass a Struct
object as an input parameter to a prepared statement.

Metadata

The type code STRUCT 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 structured data
types.
An SQL structured type must be defined as part of a particular database schema
before it can be used in a schema table definition. Information on schema-specific
user-defined types—of which STRUCT types are one particular kind—can be
retrieved by calling the DatabaseMetaData.getUDTs method. For example,

CODE EXAMPLE 16-1 returns descriptions of all the SQL structured types defined in
the catalog-name.schema-name schema.

int[] types = {Types.STRUCT};
ResultSet rs = dmd.getUDTs("catalog-name", "schema-name",
"%", types);


CODE EXAMPLE 16-12 Querying a DatabaseMetaData object for structured types
If the driver does not support UDTs or no matching UDTs are found, an empty result
set is returned. See section 16.6.3 for a description of the result set returned by the
method getUDTs.
When the DATA_TYPE returned by getUDTs is Types.STRUCT, the CLASS_NAME
column contains the fully qualified Java class name of a Java class. Instances of this
class are manufactured by the JDBC driver when getObject is called on a column
of this STRUCT type. Thus, CLASS_NAME defaults to java.sql.Struct for
structured types. If there is a custom mapping for the STRUCT type, CLASS_NAME
will be the implementation of the interface SQLData that specifies the mapping. The
JDBC API does not prohibit a driver from returning a subtype of the class named by
CLASS_NAME.
Chapter 17 “Customized Type Mapping” provides more information
about implementations of the SQLData interface.

No comments: