Sei sulla pagina 1di 96

Inheritance

Objects Enhancements 1-1


Objectives

After completing this lesson you should be


able to describe:

•Type inheritance
•Substitutability
•Method overloading and overriding
•Dynamic method dispatch
•View hierarchies

Objects Enhancements 1-2


Overview

• Type Inheritance is a way for organizing types


analogous to the way types can be used for
organizing objects.
• In Oracle9i the functionality of types has been
extended to support inheritance thus
completing the objects functionality of the
Oracle database.
• This lesson discusses the terminology, syntax
extensions, SQL operators and object
functionality in Oracle9i.

Objects Enhancements 1-3


Defining Type Inheritance

Type inheritance
• Allows sharing similarities between types as
well as extending their characteristics
• Consists of supertypes and subtypes
• Subtypes inherit the characteristics of
supertypes
• Subtypes may also have their own attributes
and methods
• Subtypes can be substituted for supertypes in
code

Type Inheritance Methodology


Type Inheritance allows sharing similarities between types as well as extending their characteristics.
Object applications typically are organized into types and type hierarchies consisting of supertypes and
subtypes. A supertype is an object and a subtype is another object which has inherited from(extended)
from one supertype. A subtype inherits all its supertype's attributes and methods. A subtype may also
add new attributes and methods of its own. All attributes and methods of a type are accessible by other
methods in the same type and its subtype(s) or to methods that have access to that type.
A subtype may override any method in its supertype chain. The subtype value appears to the
surrounding code just like the value of the supertype would, even if it uses separate mechanisms within
its specialization methods. Instance substitutability refers to the ability to use an object value of a
subtype in a context declared in terms of a supertype. Ref substitutability refers to the ability to use a
REF to a subtype in a context declared in terms of a REF to a supertype.
Please Refer to Appendix A for a listing of Object Oriented Terminology in Oracle

Objects Enhancements 1-4


Applications for Type Inheritance

• Inheritance is a crucial feature that will promote a


wider adoption of the objects technology
• Type Inheritance enables the mapping of object
models completely within the database.
• It allows the extensibility of object attributes to
other objects.
• Type Inheritance provides the ability for users to
extend their existing data model and define new
attributes.
• Better support for C++, Java applications

Objects Enhancements 1-5


Type Inheritance

• Based on the SQL: 1999 inheritance model


• Single Inheritance Model

Objects Enhancements 1-6


Inheritance Terminology

Base
ROOT
A Parent
Supertype

Derived Derived Base


Child
Subtype
B C Child
Subtype
Parent
Supertype

Derived
D Child
Subtype

Inheritance Terminology
Different people use different words to mean the same thing with inheritance. Some people talk about base
and derived classes, some talk about superclasses and subclasses, and others keep it nice and simple and
speak of parent and child classes.
In this course the terms supertype and subtype are used. Therefore, before going any further, the diagram
in the slide shows how these terms compare. Class C is derived from type A, and type D is derived from
type C. This means that D inherits all the features of C, which in turn inherits all the members of A.

Objects Enhancements 1-7


Sample Inheritance Hierarchy

Super_type

attribute
Add behavior

Sub_type1 Sub_type2
attribute attribute
attribute
Modify behavior

Leaf_type1 Leaf_type2 Leaf_type3


Objects
attribute attribute attribute you use
attribute attribute attribute

Sample Inheritance Hierarchy


The Supertype (or Base Class)
The simple example in the slide illustrates the capabilities of inheritance in an Object-Oriented application.
The base class super_type, provides basic attributes which are supported by all subtypes. Every type
derived from the super_type inherits these attributes.
Subtypes (Derived Classes)
Subtypes inherit the features of super types and can add new features too. Sub_type1 and sub_type2 are
both sub types of super_type, and they both inherit the basic attributes. Subtypes can also specify
additional methods and attributes if necessary. Subtypes can also redefine operations by overriding the
methods of the super type
Can a Subtype Inherit Just Part of a Supertype?
The simple answer to this question is no; once you make the decision to derive from a type, you
automatically inherit all of its attributes and methods, whether you like it or not.

Objects Enhancements 1-8


Type Hierarchy
Super Type

Category_typ

Sub Types
subcategory_ref_list_type

Composite_categories_typ

Leaf Type

Catalog_typ
Leaf_category_typ

Type Hierarchy
An object type can be created as a subtype of an existing object type. This is based on a single
inheritance model which means that the subtype can be derived from only one parent type. A type
inherits all the attributes and methods of its direct supertype. It can add new attributes and methods and
further, override any of the inherited methods. The above figure illustrates two subtypes
LEAF_CATEGORY_TYP and SUBCATEGORY_REF_LIST_TYP created under CATEGORY_TYP.
Further a subtype can itself be refined by defining another subtype under it thus forming type hierarchies.
COMPOSITE_CATEGORIES_TYP is a subtype of CATEGORY_TYP with attributes of
type SUBCATEGORY_REF_LIST_TYP. CATALOG_TYP is a subtype of
COMPOSITE_CATEGORIES_TYP.
The signatures are as follows:
CREATE TYPE category_typ AS OBJECT
( category_name VARCHAR2(50)
, category_description VARCHAR2(1000)
, category_id NUMBER(2)
) NOT INSTANTIABLE NOT FINAL;
CREATE TYPE subcategory_ref_list_typ AS TABLE OF REF category_ty p;
CREATE TYPE product_ref_list_typ AS TABLE OF NUMBER(6);
CREATE TYPE leaf_category_typ UNDER category_typ (
product_ref_list product_ref_list_typ );
CREATE TYPE composite_category_typ UNDER category_typ(
subcategory_ref_list subcategory_ref_list_typ
)NOT FINAL;
CREATE TYPE catalog_typ UNDER composite_category_typ (
MEMBER FUNCTION getCatalogName RETURN varchar2 );

Objects Enhancements 1-9


Type Declarations

Type Declaration can be of the following types


– FINAL – cannot have subtypes
– NOT FINAL – can have subtypes
– INSTANTIABLE - has constructor
– NOT INSTANTIABLE – no constructor

Objects Enhancements 1-10


FINAL and NOT FINAL Types
• A type declaration must have the NOT FINAL
keyword to have subtypes
• A NOT FINAL type can nest to multiple levels
• A type declaration is FINAL by default for
backward compatibility requirements.

CREATE
CREATE TYPE
TYPE category_typ
category_typ AS
AS OBJECT
OBJECT
(category_name
(category_name varchar2(50),
varchar2(50),
category_description
category_description varchar2(1000)
varchar2(1000) ,,
category_id
category_id number(2)
number(2)
))
NOT
NOT FINAL;
FINAL;

FINAL and NOT FINAL Types


In the above example type category_typ is defined as a NOT FINAL type. This implies that we can
define subtypes of category_typ. Final types can be altered and defined as not final. Similarly a not final
type with no subtypes can be altered to a final type.

Objects Enhancements 1-11


NOT INSTANTIABLE Types
• There is no constructor for a NOT INSTANTIABLE
type.
• It is not be possible to create instances of this
type.
• The typical usage would be define instantiable
subtypes which are used to populate the type.
CREATE
CREATE TYPE
TYPE category_typ
category_typ AS
AS OBJECT
OBJECT
(category_name
(category_name varchar2(50)
varchar2(50) ,,
category_description
category_description varchar2(1000),
varchar2(1000),
category_id
category_id number(2)
number(2)
))
NOT
NOT INSTANTIABLE
INSTANTIABLE NOT
NOT FINAL;
FINAL;

NOT INSTANTIABLE Types and Methods


In the above example category_typ has been created as NOT INSTANTIABLE. A method of a type can
be defined to be not instantiable. Declaring a method as not instantiable means that the type is not
providing an implementation for that method. Further, a type that contains any non instantiable methods
must necessarily be declared as not instantiable.

Example
CREATE TYPE category_typ AS OBJECT
( category_name VARCHAR2(50)
, category_description VARCHAR2(1000)
, category_id number(2)
NOT INSTANTIABLE MEMBER FUNCTION func1() RETURN NUMBER)
NOT INSTANTIABLE;

A subtype of a not instantiable type can override any of the non instantiable methods of the supertype
and provide concrete implementations. If there are any non instantiable methods remaining, the subtype
must also necessarily be declared as not instantiable. A non instantiable subtype can be defined under
an instantiable supertype. Declaring a non instantiable type to be final is not useful and will be
disallowed.

Objects Enhancements 1-12


NOT INSTANTIABLE Methods

• A method of a type can be defined to be non-


instantiable
• This implies that the type does not provide an
implementation for the method
• A type with NOT INSTANTIABLE methods is
NOT INSTANTIABLE

Objects Enhancements 1-13


Substitutability

• Ability for a supertype container to hold


subtype instances
– Instance substitutability
– REF substitutability
• Examples
– Object and REF columns
– Collection elements
– Method parameters
– PL/SQL variables etc.

Objects Enhancements 1-14


Attribute Inheritance

• Subtypes automatically inherit all attributes


declared in their supertypes
• New attributes can be declared in subtypes but
their names must be different than the names
of attributes and methods declared in the
supertype chain

Example of Attribute Inheritance


CREATE TYPE leaf_category_typ under category_typ
( product_ref_list product_ref_list_typ
);

Leaf_category_typ is created as a subtype of category_typ. Therefore an instance of leaf_category_typ


has all the attributes of category_typ in addition to the new attributes that are declared within
leaf_category_typ. Similarly, the statement below creates another subtype composite_category_typ
under category_typ.

CREATE TYPE composite_category_typ under category_typ


(
subcategory_ref_list subcategory_ref_list_typ
)
NOT FINAL;

In the above examples product_ref_list_typ and subcategory_ref_list_typ


are defined as follows
CREATE TYPE product_ref_list_typ AS TABLE OF NUMBER(6);
CREATE TYPE subcategory_ref_list_typ AS TABLE OF REF category_ty p;

Objects Enhancements 1-15


Method Inheritance

• A subtype automatically inherits all methods


declared in its supertype.
• It can also declare new methods or declare
new overloads for the methods inherited from
its supertype.

Objects Enhancements 1-16


Example of Method Inheritance

CREATE
CREATE TYPE
TYPE category_typ
category_typ AS
AS OBJECT
OBJECT
(( category_name
category_name varchar2(50)
varchar2(50)
,, category_description
category_description varchar2(1000)
varchar2(1000)
,, category_id
category_id number(2)
number(2)
MEMBER
MEMBER PROCEDURE
PROCEDURE cat_proc
cat_proc (( id
id number),…
number),… ))
NOT
NOT FINAL;
FINAL;

CREATE
CREATE TYPE
TYPE leaf_category_typ
leaf_category_typ under
under category_typ
category_typ
((
product_ref_list
product_ref_list product_ref_list_typ
product_ref_list_typ
MEMBER
MEMBER PROCEDURE
PROCEDURE cat_proc
cat_proc (( id
id number)
number)
STATIC
STATIC FUNCTION
FUNCTION cat_func
cat_func (…)
(…)
);
);

Example of Method Inheritance


The above slide illustrates method inheritance. LEAF_CATEGORY_TYP is created as a subtype of
CATEGORY_TYP and inherits the procedure CAT_PROC.
In the above examples product_ref_list_typ is defined as follows
CREATE TYPE product_ref_list_typ AS TABLE OF NUMBER(6);

Objects Enhancements 1-17


Method Override

• A subtype can redefine methods that are


defined in the supertype
• Methods declared as FINAL in the supertype
cannot be overridden in the subtype
• All methods of a FINAL type are FINAL.
• Methods of a NOT FINAL type are NOT FINAL
by default.
• Virtual (dynamic) method dispatch occurs at
runtime

Objects Enhancements 1-18


Example of Method Override
CREATE
CREATE TYPE
TYPE category_typ
category_typ AS
AS OBJECT
OBJECT
(( category_name
category_name varchar2(50)
varchar2(50)
,, category_description
category_description varchar2(1000)
varchar2(1000)
,, category_id
category_id number(2)
number(2)
MEMBER
MEMBER PROCEDURE
PROCEDURE cat_proc(),
cat_proc(),
FINAL
FINAL MEMBER
MEMBER PROCEDURE
PROCEDURE line_num
line_num (id
(id number),
number),
…)
…) );
);

CREATE
CREATE TYPE
TYPE leaf_category_typ
leaf_category_typ under
under category_typ
category_typ
((
product_ref_list
product_ref_list product_ref_list_typ
product_ref_list_typ
OVERRIDING
OVERRIDING MEMBER
MEMBER PROCEDURE
PROCEDURE cat_proc()
cat_proc()
);
);

Example of Method Override


The above slide illustrates method overriding. LEAF_CATEGORY_TYP is created as a subtype of
CATEGORY_TYP and inherits the procedure CAT_PROC. However this procedure is overridden in the
subtype by specifying the keyword OVERRIDING.

In the above examples product_ref_list_typ is defined as follows


CREATE TYPE product_ref_list_typ AS TABLE OF NUMBER(6);

Objects Enhancements 1-19


Dynamic Method Dispatch

• A method invoked on an object is dispatched


to the specific implementation based on the
runtime type, also called Most Specific Type,
of the object (polymorphism)
• For example:
DECLARE
DECLARE
v_cat_t
v_cat_t category_typ;
category_typ;
BEGIN
BEGIN
v_cat_t
v_cat_t :=
:= category_typ(…);
category_typ(…); --
-- MST
MST =category_typ
=category_typ
v_cat_t.cat_proc()
v_cat_t.cat_proc() ;; --
-- invokes
invokes category_typ
category_typ
v_cat_t
v_cat_t :=
:= leaf_category_typ();
leaf_category_typ(); --
-- MST
MST =Sub
=Sub Type
Type
v_cat_t.cat_proc();
v_cat_t.cat_proc(); --
-- invokes
invokes leaf_category_typ
leaf_category_typ
END;
END;

Dynamic Method Dispatch


In the above example the method being invoked is based on the runtime value of the variable
var_t; The runtime type is otherwise known as Most Specific Type.

Objects Enhancements 1-20


Rights Model

• A subtype has the same rights model as the


supertype
• Types declared under definers rights must
reside under the same schema
• Types declared under invoker rights can span
schemas

Objects Enhancements 1-21


Example of Definers Rights Model

CREATE
CREATE TYPE
TYPE category_typ
category_typ AS
AS OBJECT
OBJECT (…);
(…);
--definers
--definers rights
rights type
type

CREATE
CREATE TYPE
TYPE leaf_category_typ
leaf_category_typ UNDER
UNDER category_typ
category_typ
(…)
(…) ;; --
-- subtype
subtype in
in same
same schema
schema as
as supertype
supertype

CREATE
CREATE TYPE
TYPE schema1.composite_category_typ
schema1.composite_category_typ UNDER
UNDER
category_typ(…)
category_typ(…) ;; --
-- causes
causes error
error

Example of Definers Rights Model


In the above slide. CATEGORY_TYP is the supertype created under definers rights.
LEAF_CATEGORY_TYP is the sub_type under CATEGORY_TYP and is created in the same schema.
COMPOSITE_CATEGORY_TYP is also a subtype under CATEGORY_TYP but the creation of this type
will fail because it is not in the same schema.

Objects Enhancements 1-22


Example of Invokers Rights Model

CREATE
CREATE TYPE
TYPE category_typ
category_typ AUTHID
AUTHID CURRENT_USER
CURRENT_USER AS
AS
OBJECT
OBJECT (…);
(…); --
-- Invoker
Invoker rights
rights type
type

CREATE
CREATE TYPE
TYPE schema2.composite_category_typ
schema2.composite_category_typ UNDER
UNDER
category_typ(…);
category_typ(…); --
-- LEGAL
LEGAL

Example of Invokers Rights Model


In the above example both the supertype and the subtype are created under invokers rights.Therefore it
is possible to create them in different schemas.

Objects Enhancements 1-23


Object and REF Assignment

An object/ REF value may be assigned to an


object /REF container when
– The source and the target types are
identical.
– The source type is a subtype of the target
type (implicit widening)
– The source type is a supertype of the target
type (narrowing). This requires the use of
the TREAT operator.

Objects Enhancements 1-24


Example of Widening
CREATE
CREATE TABLE
TABLE categories_tab
categories_tab ((
catmain
catmain category_typ,
category_typ, --create
--create an
an object
object table
table
catleaf
catleaf leaf_category_typ,
leaf_category_typ,
catcomp
catcomp composite_category_typ
composite_category_typ );
);

UPDATE
UPDATE categories_tab
categories_tab
SET
SET catmain
catmain == catleaf;
catleaf; --
-- assigning
assigning sub
sub type
type to
to
--supertype
--supertype
DECLARE
DECLARE
var1
var1 category_typ;
category_typ;
var2
var2 leaf_category_typ;
leaf_category_typ;
BEGIN
BEGIN --
-- assigning
assigning sub
sub type
type
var1
var1 :=
:= var2;
var2; --
-- to
to supertype
supertype
END;
END;

Objects Enhancements 1-25


Example of Narrowing Using Treat

--
-- updating
updating supertype
supertype with
with subtype
subtype
UPDATE
UPDATE categories_tab
categories_tab set
set catcomp
catcomp == TREAT
TREAT
(catmain
(catmain as
as composite_category_typ);
composite_category_typ);
--
-- assigning
assigning supertype
supertype to
to subtype
subtype
DECLARE
DECLARE
var1
var1 category_typ;
category_typ;
var2
var2 leaf_category_typ;
leaf_category_typ;

BEGIN
BEGIN
var2
var2 :=
:= TREAT(var1
TREAT(var1 as
as leaf_category_typ);
leaf_category_typ);
END;
END;

Objects Enhancements 1-26


Object Assignment - Collections

• A collection may be assigned to another


collection of the same type
• The source and destination must be of the
same type
• A subtype element may be assigned to a
collection

Objects Enhancements 1-27


Example of Collection Assignment

CREATE
CREATE TYPE
TYPE cat_tab
cat_tab AS
AS TABLE
TABLE OF
OF category_typ;
category_typ;
--supertype
--supertype
CREATE
CREATE TYPE
TYPE leaf_cat_tab
leaf_cat_tab AS
AS TABLE
TABLE OF
OF leaf_category_typ;
leaf_category_typ;
--subtype
--subtype

DECLARE
DECLARE
v_cat_tab
v_cat_tab cat_tab
cat_tab ;;
v_leaf_cat_tab
v_leaf_cat_tab leaf_cat_tab;
leaf_cat_tab;
v_cat_elem
v_cat_elem category_typ;
category_typ;
v_leaf_cat_elem
v_leaf_cat_elem leaf_category_typ;
leaf_category_typ;
BEGIN
BEGIN
v_cat_tab
v_cat_tab :: == v_leaf_cat_tab
v_leaf_cat_tab ;;--ILLEGAL
--ILLEGAL not
not same
same type
type
v_cat_tab
v_cat_tab :=
:= cat_tab
cat_tab (v_cat_elem,
(v_cat_elem, v_leaf_cat_elem);
v_leaf_cat_elem);
--LEGAL
--LEGAL elements
elements of
of subtype
subtype
END;
END;

Objects Enhancements 1-28


Review of Object Views

• An object view is a virtual object table.


• Each row in the view is an object
• Object views are useful in prototyping or
transitioning to object-oriented applications
• Object views can be used like relational views
to present only the data that you want users to
see.
• Using object views can lead to better
performance.

Review of Object Views


Object views were introduced in Oracle8i. An object view is a virtual object table. Each row in the view
is an object: you can call its methods, access its attributes using dot notation, and create a REF that
points to it.
Object views are useful in prototyping or transitioning to object-oriented applications because the data in
the view can be taken from relational tables and accessed as if the table were defined as an object table.
You can run object-oriented applications without converting existing tables to a different physical
structure.
Object views can be used like relational views to present only the data that you want users to see. For
example, you might create an object view that presents selected data from an employee table but omits
sensitive data about salaries.
Using object views can lead to better performance. Relational data that make up a row of an object view
traverse the network as a unit, potentially saving many round trips.
REFERENCE
Note: for more information on object views please refer Oracle9i documentation :
Oracle9i Application Developer's Guide - Object-Relational Features

Objects Enhancements 1-29


Object View Hierarchies

• An object view hierarchy is a set of object


views each of which is based on a different
type in a type hierarchy.
• Subviews are created under a superview,
similar to the way subtypes are created under
a supertype in a type hierarchy.
• Each object view is populated with objects of a
single type, but queries on a given view
references all subviews as well.

Object View Hierarchies


An object view hierarchy is a set of object views each of which is based on a different type in a type
hierarchy. Subviews in a view hierarchy are created under a superview, analogous to the way subtypes
in a type hierarchy are created under a supertype.
Each object view in a view hierarchy is populated with objects of a single type, but queries on a given
view implicitly address its subviews as well. Thus an object view hierarchy gives you a simple way to
frame queries that can return a polymorphic set of objects of a given level of specialization or greater.

Objects Enhancements 1-30


Restrictions on Object View Hierarchies

• Object views can be created as subviews of


another object view
• The superview must be an immediate
supertype of the object view being created.
• The view hierarchy does not have to span the
entire corresponding type hierarchy
• Two different object view hierarchies cannot
each have a subview based on the same
subtype.

Restrictions on Object View Hierarchies


The root view of an object view hierarchy can be based on any type in a type hierarchy not necessarily
the root type. The object view hierarchy does not have to extend to every leaf of a type hierarchy or
cover every branch. However intervening subtypes in the line of descent cannot be skipped. Any
subview must be based on a direct subtype of the type of its direct superview.
Similar to a type hierarchy, an object view can have multiple sibling subviews. But a subview based on
a given type can participate in only one object view hierarchy; two different object view hierarchies
cannot each have a subview based on the same subtype.
A subview inherits the object identifier (OID) from its superview. An OID cannot be explicitly specified
in any subview. A root view can explicitly specify an object identifier using the WITH OBJECT ID
clause. If the OID is system-generated or the clause is not specified in the root view, then subviews can
be created only if the root view is based on a table or view that also uses a system generated OID. The
query underlying a view determines whether the view is updatable. For a view to be updatable, its query
must contain no joins, set operators, aggregate functions, GROUP BY, DISTINCT, pseudocolumns, or
expressions. The same applies to subviews. If a view is not updatable, you can define INSTEAD OF
triggers to perform appropriate DML actions. INSTEAD OF triggers are not inherited by subviews. All
views in a view hierarchy must be in the same schema.

Objects Enhancements 1-31


Creating Object View Hierarchies

• Subviews can be created using the UNDER


keyword.
• The two possible approaches are:
– "Flat" model - all the views in the hierarchy
are based on the same table.
– "Horizontal" model - each view is based on
a different table.

Objects Enhancements 1-32


Query/ DML on Object Views

• Queries or DML on an object view access


objects from the specific view and all its
subviews
– Polymorphic set of objects
• Can be restricted to a specific view in the
hierarchy with the ONLY qualifier in the FROM
clause
• New operators in Oracle9i
– TREAT
– IS OF

Objects Enhancements 1-33


Inheritance Support in Data Dictionary

The following views have been enhanced to


support inheritance, substitutability and type
evolution:
• {USER|ALL|DBA} _TYPES
• {USER|ALL|DBA} _TYPE_ATTRIBUTES
• {USER|ALL|DBA} _TYPE_METHODS

Inheritance Support in Data Dictionary


The following are the descriptions of these views:
USER_TYPES includes the following columns ATTRIBUTES, METHODS, PREDEFINED,
INCOMPLETE, FINAL, INSTANTIABLE, SUPERTYPE_OWNER, SUPERTYPE_NAME ,
LOCAL_ATTRIBUTES and LOCAL_METHODS which help to track the inheritance hierarchy.
USER_TYPE_METHODS includes FINAL,INSTANTIABLE, OVERRIDING, INHERITED
which help track method inheritance
USER_TYPE_ATTRS includes ATTR_TYPE_OWNER and INHERITED which help track attribute
inheritance.

Objects Enhancements 1-34


Client Environments
• Support for
– Access and manipulation of subtype instances
– REF and instance substitutability
• Accessible through multiple language
environments
– PL/SQL
– JAVA via JDBC
– C/C++ via OCI/OCCI
– Pro*C, SQLJ
• Translator Support is provide by OTT (C/C++),
JPublisher (Java)

Objects Enhancements 1-35


Inheritance Support in Java

• Oracle9i introduces a new SQL type called


SQLJ which is fully implemented in Java
• The SQLJ object type supports inheritance
feature with certain restrictions

REFERENCE
Note : For more information on SQLJ Object types please refer to the lesson on SQLJ object
types in the Objects module

Objects Enhancements 1-36


Benefits of Inheritance

• Sharing - provides efficiency in development


time and improves manageability of
applications.
• Extensibility- provides flexibility and power of
expression to solving application problems.
• Substitutability - allows a value of some
subtype to be used by code originally written
for the supertype, without any knowledge of
the subtype being needed in advance.

Objects Enhancements 1-37


Summary

In this lesson, you should have learned about


•Type inheritance
•Substitutability
•Method overloading and overriding
•Dynamic method dispatch
•View hierarchies

Objects Enhancements 1-38


Type Evolution

Objects Enhancements 2-1


Objectives

After this lesson you should be able to describe:

• Propagating a type change


• Table validation
• Type evolution

Objectives
In prior releases an object type referenced by a table or user-defined type could only be
changed by adding methods to it. In Oracle9i objects can evolve more freely and any changes
made to a type can propagate to schema objects referencing it. Oracle9i provides the ability to
add, drop and modify attributes of an object type.

Objects Enhancements 2-2


Overview

• In prior releases an object type referenced by


a table or user-defined type can only be
changed by adding methods to it.
• In Oracle9i objects can evolve more freely and
any changes made to a type can propagate to
schema objects referencing it.
• In Oracle9i attributes and methods of an
object type can be
– Added
– Dropped
– Modified

Objects Enhancements 2-3


Type Dependencies

• A user defined type can be referenced by:


– Tables or views
– Types or subtypes
– Program units
– Indextypes
– Functional indexes
– Operators
• Any object that references a type is a
dependent object

Type Dependencies
Any object that references a type is considered a dependent object. When a type is modified all
dependent program units, views, operators and indextypes are marked invalid. Some objects are
automatically revalidated the next time that they are accessed. It the recompilation is successful then the
objects become valid again. However when a type has either type or table dependent, altering the type
definition becomes more complicated due to existing persisting data which relies on the current type
definition. To support this functionality the ALTER TYPE statement has additional options to allow
changes to an object type to be propagated to its dependent types and tables.

Objects Enhancements 2-4


Propagating Type Changes

Type changes are divided into two categories:


• Non-structural changes - changes that do not
affect the table data such as adding or
dropping a method.
• Structural changes - changes that affect the
structure of tables and the data such as adding
or dropping attributes from a type.

Objects Enhancements 2-5


Propagating Structural Changes

• Non-structural changes do not create a new


version of the type
• All dependent objects immediately become
INVALID
• Dependent objects can be validated by
recompilation
• Dependent table data is unaffected

Objects Enhancements 2-6


Propagating Structural Changes

Propagating structural changes is a four step


process completed in memory a row at a time
1. A new version for each valid dependent
type is created
2. All views, indextypes , operators, domain
indexes and program units which depend
on the target type are invalidated
3. The structure of all dependent tables is
upgraded to the latest version of each
referenced type
4. The column data is converted to the format
of the latest type version

Propagating Structural Changes


A structural type change requires creating a new version of the type and propagating the change to
dependent objects. This involves the following steps:
•A new version for each valid dependent type is created so each one references the latest version of the
altered type. This is done before converting dependent tables to ensure that the latest version of each
referenced type is used.
•All views, indextypes, operators, domain indexes and program units which depend directly or
indirectly on the target type are invalidated so they can be recompiled based on the latest version of the
type.
•The structure of all dependent tables are upgraded to the latest version of each referenced type. For
each attribute added to a type, one or more internal columns will be added to the table depending on the
new attribute's type. New attributes will be added as NULL. For each modified attribute, the type of its
associated column will be changed accordingly.
•The data stored in columns which directly or indirectly reference the altered type is converted to the
latest version format.

Objects Enhancements 2-7


Altering a Type's Attributes

ALTER
ALTER TYPE
TYPE type_name
type_name
[ADD
[ADD || DROP
DROP || MODIFY|RENAME]
MODIFY|RENAME]
{{ method_spec
method_spec || attribute_spec
attribute_spec }}
[INVALIDATE
[INVALIDATE ||
CASCADE
CASCADE [[NOT]
[[NOT] INCLUDING
INCLUDING TABLE
TABLE DATA]
DATA]
[FORCE]
[FORCE] EXCEPTIONS
EXCEPTIONS INTO
INTO <table_name>
<table_name>
];
];

Syntax for Altering a Type's Attributes


New Keywords and Parameters
ADD adds specified method to type
DROP drops the method with the specified spec from the target
RENAME renames the method with the specified spec from the target
ADD ATTRIBUTE adds specified attribute to the target type
DROP ATTRIBUTE drops specified attribute from the target type
MODIFY ATTRIBUTE modifies the type of the specified attribute
INVALIDATE alters target type and invalidates all dependent objects without
checking dependent types and tables whether the type change may
cause any problems
CASCADE alters target type and propagates the type change to dependent types
and tables
INCLUDING T ABLE DATA converts data stored in all user -defined columns to the most recent
version of the column's type
NOT INCLUDING DATA leaves the column data unchanged FORCE forces errors from
dependent tables to be ignored

Objects Enhancements 2-8


Table Validation

ALTER
ALTER TABLE
TABLE table_name
table_name
UPGRADE
UPGRADE [[NOT]
[[NOT] INCLUDING
INCLUDING DATA]
DATA]
[column_storage_clause];
[column_storage_clause];

New Keywords and Parameters


UPGRADE: converts the metadata of the target table to conform with the latest version of each
referenced type.

INCLUDING DATA: Converts data stored in all user-defined columns to the most recent version of
the column's type.

NOT INCLUDING DATA: leaves column data unchanged.

COLUMN_STORAGE_CLAUSE : specifies the storage for the new VARRAY , nested table or LOB
attributes to be added to the table.

Objects Enhancements 2-9


ALTER TYPE Statement Options
ALTER TYPE

Target Type
INVALIDATE

CASCADE Dependent
NOT Types
INCLUDING
TABLE DATA

Metadata Metadata
2

CASCADE
INCLUDING Dependent
TABLE Tables
DATA

3
Other
Dependent
Objects

ALTER TYPE Statement Options

INVALIDATE: All objects below line 1 are marked invalid.


CASCADE NOT INCLUDING TABLE DATA: All objects below line 2 are marked
invalid. All dependent tables are upgraded to the latest type version but the table data
are not converted.
CASCADE INCLUDING TABLE DATA: All objects below line 3 are marked
invalid. All dependent tables are upgraded to the latest type version including the table
data.

Objects Enhancements 2-10


Sample Schema for Type Evolution - No
Dependent Tables
Category_typ

Leaf_category_typ

Sample Schema for Type Evolution - No Dependent Tables


Category_typ is the root type created as follows:
CREATE TYPE category_typ AS OBJECT
( category_name VARCHAR2(50)
, category_description VARCHAR2(1000)
, category_id number(2)
)
NOT FINAL;
Leaf_category-typ is the subtype of category_typ created as follows:
CREATE TYPE leaf_category_typ UNDER category_typ
( product_ref_list product_ref_list_ typ
);
Where Product_ref_list is a type table created as follows:
CREATE TYPE product_ref_list_typ AS TABLE OF number(6);

Objects Enhancements 2-11


Examples Of Schema Evolution With NO
Dependent Tables

Altering types with no dependents (leaf)

ALTER
ALTER TYPE
TYPE leaf_category_typ
leaf_category_typ
ADD
ADD ATTRIBUTE
ATTRIBUTE (( skew
skew number);
number);

Altering types with cascade option -


dependents are automatically updated

ALTER
ALTER TYPE
TYPE category_type
category_type ADD
ADD attribute
attribute
(skew
(skew number)
number) CASCADE;
CASCADE;

Examples Of Schema Evolution- NO Dependent Tables


In the first example a new attribute is added to leaf_category_typ. Since leaf_category_typ does not
have any dependents no other options need to be specified.
In the second example a new attribute is added to categories_typ and the cascade option is used to
propagate the changes to its non table dependents.

Objects Enhancements 2-12


Type Extension with Dependent Tables

Category_typ

Categories_tab
Leaf_category_typ

Schema Evolution
Category_tab is created as a table of category_typ as follows:
CREATE TABLE categories_tab OF category_typ NOT SUBSTITUTABLE
AT ALL LEVELS
( category_id primary key
);

Objects Enhancements 2-13


Propagating Changes to Dependent Tables

Altering types without converting column data


in dependent tables

ALTER
ALTER TYPE
TYPE category_typ
category_typ
ADD
ADD ATTRIBUTE
ATTRIBUTE (( hiredate
hiredate DATE)
DATE)
CASCADE
CASCADE NOT
NOT INCLUDING
INCLUDING TABLE
TABLE DATA;
DATA;

Upgrading a table's structure, including its


column data, to the latest type version.

ALTER
ALTER TABLE
TABLE category_tab
category_tab UPGRADE
UPGRADE
INCLUDING
INCLUDING DATA;
DATA;

Propagating Changes to Dependent Tables


In the above example a new attribute is added to category_typ. The data in the table is not converted
because the option NOT INCLUDING TABLE DATA is specified. This is a good option when there
are a large number of dependent tables because during the UPGRADE all dependent tables will be
locked. Instead, by deferring the UPGRADE, the data of each independent table can be later converted
by using the "ALTER TABLE… UPGRADE"statement locking only one table at a time. All dependent
tables will have a status of invalid until UPGRADED.

Objects Enhancements 2-14


New Dictionary Views on Type Evolution

• {USER|ALL|DBA} _PENDING_CONV_TABLES
These views lists all tables which are in an
invalid state due to altering a parent type
• {USER|ALL|DBA}_TYPE_VERSIONS
These views lists all the versions of the
types

Objects Enhancements 2-15


Summary

In this lesson, you should have learned how to:


• Alter a type and propagate the type change to
its dependent objects.
• Upgrade an invalid table to the latest type
version format.

Objects Enhancements 2-16


Multi Level Collections

Objects Enhancements 3-1


Objectives

After this lesson you should be


able to describe:
• Multi level collection types
• Tables with multi level collections
• Operations on multi level collections
• Value semantics
• Multi level collections in PL/SQL

Overview
Collections were introduced in Oracle8.0 and are complex structures such as VARRAYS and Nested
tables which can be created as columns in database tables. Oracle9i allows collections to be nested
within other collections which can be used as datatypes for variables and column of tables

Objects Enhancements 3-2


Multi Level Collection Types

• Multi level collection types are collection types


where the collection element itself is directly or
indirectly another collection type.
• Types of multi level collections are:
– Nested table of nested table/varray type
– Nested table of a varray/nested table type
– Varray of object type containing collection
– Nested table of object type containing
collection

Multi Level collection Types


Nested tables of nested table type is a type which contains another nested table as one of its attributes.
For example:j
CREATE TYPE nt_1 AS TABLE OF NUMBER;
CREATE TYPE nt_2 AS TABLE OF t_1;
Nested tables of a varray type is a type which contains a varray as one of its attributes. For example
CREATE TYPE va_1 AS VARRAY(10) OF DATE;
CREATE TYPE nt_3 AS TABLE OF va_1;
Varray of nested table type is a varray based on a nested table. For example:
CREATE TYPE va_2 AS VARRAY(10) of nt_1;
Nested table of ADT containing collection is a nested table type based on an object type containing
nested table as one of its attributes. For example:
CREATE TYPE t_1 AS OBJECT ( a number,
b date,
c nt_1);

CREATE TYPE nt_4 AS TABLE of t_1;

Objects Enhancements 3-3


Applications of Multi Level Collections

• Multi level collections can be used to represent


nested one-to-many relationships.
• An one-to-many relationship can be
represented by a single collection.
• If each element of the collection has another
one-to-many relationship, then this will require
a multi level collection.
• This allows the representation of multiple
levels of information in one object table.

Objects Enhancements 3-4


Examples of Multi Level Collections

CUSTOMERS_DRILL CUST_ORDERS ORDER_ITEMS_LIST


DOWN

Examples of Multi Level Collections


In the above diagram CUSTOMERS is a nested table with CUST_ORDERS as a column. CUST_ORDERS
is a nested table type with ORDER_LIST_TYP as a column and ORDER_ITEMS_LIST is an object
table with order information

Objects Enhancements 3-5


Creating Multi Level Collections

CREATE
CREATE TYPE
TYPE order_item_typ
order_item_typ AS
AS OBJECT
OBJECT
(( line_item_id
line_item_id NUMBER(3)
NUMBER(3)
,, unit_price
unit_price NUMBER(8,2)
NUMBER(8,2)
,, quantity
quantity NUMBER(8)
NUMBER(8)
);
);

CREATE
CREATE TYPE
TYPE order_item_list_typ
order_item_list_typ AS
AS TABLE
TABLE OF
OF
order_item_typ;
order_item_typ;

CREATE
CREATE TYPE
TYPE order_typ
order_typ AS
AS OBJECT
OBJECT
(( order_id
order_id NUMBER(12)
NUMBER(12)
,, order_item_list
order_item_list order_item_list_typ
order_item_list_typ
)) ;;

CREATE
CREATE TYPE
TYPE order_list_typ
order_list_typ AS
AS TABLE
TABLE OF
OF order_typ;
order_typ;

Objects Enhancements 3-6


Tables with Multi Level Collections

• Nested collections can be used as columns in


database tables
• The nested table storage clause can be
used to specify the characteristics of the inner
collections
• A store table is created for each nested table.
The physical attributes of the store table can
be specified in the nested table storage
clause

Objects Enhancements 3-7


Creating Tables with Multi Level Collections

CREATE
CREATE TABLE
TABLE customers_drilldown
customers_drilldown
(( customer_id
customer_id NUMBER(6)
NUMBER(6)
,, cust_first_name
cust_first_name VARCHAR2(20)
VARCHAR2(20)
,, cust_last_name
cust_last_name VARCHAR2(20)
VARCHAR2(20)
,, cust_address
cust_address VARCHAR2(45)
VARCHAR2(45)
,, phone_numbers
phone_numbers VARCHAR2(15)
VARCHAR2(15)
,, credit_limit
credit_limit NUMBER(9,2)
NUMBER(9,2)
,, cust_orders
cust_orders order_list_typ)
order_list_typ)
NESTED
NESTED TABLE
TABLE cust_orders
cust_orders STORE
STORE AS
AS orders_tab
orders_tab
(PRIMARY
(PRIMARY KEY
KEY (( NESTED_TABLE_ID,
NESTED_TABLE_ID, order_id)
order_id)
NESTED
NESTED TABLE
TABLE order_items_list
order_items_list STORE
STORE AS
AS
order_items_tab
order_items_tab );
);

Creating Tables with Multi Level Collections


In the above example orders_tab is a store table which is used to hold the rows corresponding to the
orders, while order_list_tab is used to store the rows for projects. A hidden setid column is created to
join the collection elements with the parent row. The columns of the orders_tab table will be
NESTED_TABLE_ID to store the SETID linking to the parent table. The columns of order_items_tab
similarly will be the NESTED_TABLE_ID to store the SETID linking to its parent table.

Objects Enhancements 3-8


Example of Collection Using
COLUMN_VALUE clause

PRODUCT_ID_TABLE SKU_TAB_T NUM_TAB_T

Examples of Multi Level Collections


In the above diagram PRODUCT_ID_TABLE is a nested table with SKU_TAB_T as a column.
SKU_TAB_T is a nested table type with NUM_TAB_T as a column and NUM_TAB_T is an object table
with line number information

Objects Enhancements 3-9


Example of Using the Column Value Clause

CREATE
CREATE TYPE
TYPE numtab_t
numtab_t AS
AS TABLE
TABLE OF
OF NUMBER;
NUMBER;

CREATE
CREATE TYPE
TYPE skutab_t
skutab_t AS
AS TABLE
TABLE OF
OF numtab_t;
numtab_t;

CREATE
CREATE TABLE
TABLE product_id_table
product_id_table as
as ((
line_number
line_number NUMBER(4),
NUMBER(4),
sku_number
sku_number skutab_t)
skutab_t)
NESTED
NESTED TABLE
TABLE sku_number
sku_number STORE
STORE AS
AS sku_table
sku_table
(NESTED
(NESTED TABLE
TABLE COLUMN_VALUE
COLUMN_VALUE STORE
STORE AS
AS
num_table);
num_table);

Example of Using the Column Value Clause


In the above example two store tables will be created for PRODUCT_ID_TABLE . The tables are named
SKU_TABLE and NUM_TABLE. The columns of sku_table will be the NESTED_TABLE_ID to store
the SETID linking to the parent table. COLUMN_VALUE is a nested table column with another hidden
SETID to link its children from num_table. COLUMN_VALUE keyword allows the definition of the
storage clause without specifying the name of the column. It is only allowed in the context of a table of
scalars

Objects Enhancements 3-10


Multi Level Collections:Varrays

• A base table can have columns of type varray.


• A varray column in a base table can either be
another varray or a nested table.
• A varray column with elements of collection
type, are stored in a LOB.
• There will be no storage table associated with
the nested table element within a varray.

Varray Columns in Multi Level Collections


A varray collection can be nested in other varray collections or in tables. Similarly a nested table can be
further nested in a varray. Varrays and Nested tables differ in several ways. A table containing a varray
column stores the entire varray as a lob . So varrays tend to be dense and for the individual elements of
the varray cannot be easily updated. Nested tables on the other hand are stored as two separate tables
and can be updated easily through DML statements. However a nested table inside a varray column
loses some of its characteristics. It cannot be manipulated through DML since the whole varray is stored
in a lob. It also cannot have indexes.

Objects Enhancements 3-11


Operations on Multi Level Collections

• Collection constructors
• Assignment and comparisons
• DML operations
• Collection unnesting

Objects Enhancements 3-12


Collection Constructors

• A collection constructor is a function that


returns a collection value whose elements are
a given list of values.
• Every collection type has a corresponding
constructor with the same name called the
default constructor.
• The elements of the constructor of a nested
collection are collection constructors as well.

Objects Enhancements 3-13


Example of Collection Constructors
INSERT
INSERT INTO
INTO customers_drilldown
customers_drilldown VALUES
VALUES
(( 101,'Constantin','Welles','514
101,'Constantin','Welles','514 WW Superior
Superior St.,
St.,
46901,
46901, Kokomo,IN,US','+1
Kokomo,IN,US','+1 317
317 123
123 4104',
4104', '100',
'100',
order_list_typ(
order_list_typ(
order_typ
order_typ (1000,
(1000, order_list_typ(
order_list_typ(
order_item_typ(
order_item_typ( 4900,
4900, 12,
12, 4),
4),
order_item_typ(
order_item_typ( 2067,
2067, 4,
4, 11 ))
))
),
),
order_typ
order_typ (1001,
(1001, order_list_typ(
order_list_typ(
order_item_typ(
order_item_typ( 3111,
3111, 25,
25, 8),
8),
order_item_typ(
order_item_typ( 2309,
2309, 10,4))
10,4))
)) )) );
);

Objects Enhancements 3-14


Assignment and Comparisons

• Collection assignment happens during data


transfers like INSERT, FETCH, UPDATE and
SELECT statements as well as in PL/SQL
assignment statements
• In collection assignments both the source and
the destination must be of the same data type
• Objects whose datatypes are collection types
cannot be compared

Note: The following slides give examples of DML assignment operations on multi level collections.

Objects Enhancements 3-15


DML Operations on Multi Level Collections

DML in multi level collections can be done in


one of the following ways
– Atomic Updates
– Piecewise Updates

DML Operations on Multi Level Collections


Atomic updates can be done on all collections whether they are nested tables or varrays. Piecewise
updates can be performed only on nested tables.

Objects Enhancements 3-16


Example of Atomic Updates

DECLARE
DECLARE
v_ords
v_ords order_list_typ;
order_list_typ;
BEGIN
BEGIN
……
--initialize
--initialize v_ords
v_ords
UPDATE
UPDATE customers_drilldown
customers_drilldown cc
SET
SET c.cust_orders
c.cust_orders == v_ords
v_ords
WHERE
WHERE customer_id
customer_id == 102;
102;
……
END
END

Example of Atomic Updates


Atomic updates treat the collection as single data items. In the above example v_ords is a bind variable.

Objects Enhancements 3-17


Examples of Piecewise Updates

--
-- Insert
Insert new
new order
order for
for customer
customer 101
101

INSERT
INSERT INTO
INTO TABLE
TABLE (SELECT
(SELECT cust_orders
cust_orders
FROM
FROM customers_drilldown
customers_drilldown WHERE
WHERE customer_id
customer_id ==
101)
101)
VALUES
VALUES (( 1010,
1010, order_list_typ(
order_list_typ(
order_item_typ(
order_item_typ( 4901,
4901, 10,
10, 2),
2),
order_item_typ(
order_item_typ( 2077,
2077, 15,
15, 22 );
);

--Insert
--Insert new
new project
project for
for employee
employee number
number 100
100

INSERT
INSERT INTO
INTO TABLE
TABLE (SELECT
(SELECT o.order_item_list
o.order_item_list
FROM
FROM TABLE(
TABLE( SELECT
SELECT cust_orders
cust_orders from
from
customers_drilldown
customers_drilldown cc where
where
customer_id=
customer_id= 101)
101) oo
VALUES
VALUES (( 4444,
4444, 10,
10, 2)));
2)));

Examples of Piecewise Updates


In the above examples the TABLE clause identifies the nested table instance that is being queried.

Objects Enhancements 3-18


Example of Collection Unnesting

• Unnesting is the process of viewing collection


data in a flat form.
• This can apply to multi level collections as well
as single level collections
• For example:

SELECT
SELECT c.customer_name
c.customer_name
FROM
FROM customers_drilldown
customers_drilldown c,
c,
TABLE(c.cust_orders)o,
TABLE(c.cust_orders)o,
TABLE(o.order_item_list)l;
TABLE(o.order_item_list)l;

Objects Enhancements 3-19


Collection Value Semantics

• Collection elements cannot be manipulated


independent of the record containing them
• Retrieving the top level collection, retrieves all
nested collections
• Deleting a row with a collection column deletes
all rows associated with that collection
• Dropping a table with a collection column
drops the corresponding inner nested tables
• Modifying a collection element logically
modifies the row containing the element

Objects Enhancements 3-20


Multi Level collections in PL/SQL

• There is no change in type compatibility


between Oracle8i and Oracle9i
• There is no special syntax to access multi level
collections
• It is possible to iterate over all elements of a
nested collection using a single subscript
notation

Objects Enhancements 3-21


Summary

In this lesson, you should have learned about


• Multi Level Collections and Types
• Tables with multi level collections
• Operations on multi level collections
• Value Semantics
• Multi level collections in PL/SQL

Objects Enhancements 3-22


SQLJ Object Type

Objects Enhancements 1
Objectives

After this lesson you should be


able to explain:
• Creating SQLJ Object type
• Receiving SQLJ Objects
• Sending SQLJ Objects
• SQLJ Object Metadata APIs

Objects Enhancements 2
Overview
• The SQLJ Part2 standard API allows access of
object relational features.
• This lesson addresses the support for using Java
classes as SQL Types and discusses the creation
of objects or columns of these types.
• It also describes the mechanism for persisting
Java classes as SQL types, which enables the user
to define columns or rows of this Java type and to
query and manipulate the objects of this type.

Objects Enhancements 3
SQLJ Objects

• SQLJ Object is a special SQL type designed fully


implemented in Java.
• Each SQLJ Object type maps to a Java class inside
the database.
• Once the mapping is registered through the
"CREATE TYPE" SQL DDL, the Java application can
INSERT/SELECT copies of the Java objects directly
into/from the database through the Oracle9i JDBC
drivers.
• The database SQL engine can access the attributes
of the Java class as a regular SQL type.

Objects Enhancements 4
Creating SQLJ Object Types

There are three steps to creating a SQLJ


object type in the database:
1. Creating the Java class implemented as
one of the following:
– SQLData
– CustomDatum
– OraData
2. loading the classes into the database with
loadjava utility
3. Creating the SQL type that maps to the
Java class

Objects Enhancements 5
Creating the SQLJ Class

• The SQLJ Class must implement one of the


following interfaces:
– java.sql.SQLData
– oracle.sql.OraData
– oracle.sql.CustomDatum

Creating the SQLJ Class


The rules to create the SQLData class or OraData/OraDataFactory classes for SQLJ Object are
indeed the same as the rules of creating the customized classes for ADTs. The customized classes (either
SQLData or OraData) provide the Java object's layout through readSQL()/writeSQL() or the
OraDataFactory implementation.
REFERENCE
Note:For more information on JDBC customized mapping, please refer to Oracle9i Working with
Oracle Object Types - Creating and Using Custom Object Classes for Oracle Objects, Oracle9i JDBC
Developer's Guild and Reference
For example, the Person Java class can be implemented as follows --
import java.sql.*;
import java.io.*;
public class Person implements SQLData
{
private String sql_type;
public int ssn;
public String name;
public String address;
public Person () {..}

Objects Enhancements 6
Creating the SQLJ Class
public String getSQLTypeName() throws SQLException {
return sql_type; }
public void readSQL(SQLInput stream, String typeName) th rows
SQLException
{
sql_type = typeName;
ssn = stream.readInt();
name = stream.readString();
address = stream.readString();
}
public void writeSQL(SQLOutput stream) throws SQLExcepti on
{
stream.writeInt (ssn);
stream.writeString (name);
stream.writeString (address);
}

// other methods
public int id () { ... }
}

Objects Enhancements 7
Loading the SQLJ Class into the Database

• After creating the Java class, it has to be made


visible to the database
• This can be done using the "loadjava" tool of
Oracle9i JVM

Objects Enhancements 8
Creating SQLJ Object Types in the Database

• The "CREATE TYPE" SQL DDL statement can


be used to create the SQLJ Objects .
• For example:
CREATE
CREATE TYPE
TYPE person_t
person_t AS
AS OBJECT
OBJECT EXTERNAL
EXTERNAL NAME
NAME
'Person'
'Person' LANGUAGE
LANGUAGE JAVA
JAVA
USING
USING SQLData
SQLData
(ss_no
(ss_no NUMBER(9)
NUMBER(9) EXTERNAL
EXTERNAL NAME
NAME 'ssn',
'ssn',
name
name VARCHAR2(100)
VARCHAR2(100) EXTERNAL
EXTERNAL NAME
NAME 'name',
'name',
address
address VARCHAR2(255)
VARCHAR2(255) EXTERNAL
EXTERNAL NAME
NAME 'address',
'address',
MEMBER
MEMBER FUNCTION
FUNCTION id()
id() RETURN
RETURN int
int EXTERNAL
EXTERNAL
NAME
NAME 'id'
'id'
);
);

Creating SQLJ Object Types in the Database


The above example creates a SQL Accessible Java Object type "PERSON_T" to represent the Java
class Person that was created previously.
The syntax specifies the following information:
• Java class name: "Person" in this case
• Representation: "SQLData" in this case
• SQL names and SQL types of the Java data fields
The SQL names are used by the database SQL engine to look into the data fields; the the SQL type
specified in each data field provides the SQL engine a hint of the data type when the SQL engine needs
to access the data fields values.

Objects Enhancements 9
Receiving SQLJ Objects

• In JDBC applications, SQLJ objects are returned


as:
– Query results from ResultSet
– PL/SQL OUT parameters from
CallableStatement
– Object type attributes from
oracle.sql.STRUCT
– Collection elements from
oracle.sql.ARRAY
• The Oracle JDBC drivers restore the SQLJ
objects back to instances of the corresponding
Java classes using getObject() and setObject()
methods.

Example of creating SQL accessible Object types and dependent object tables
CREATE TYPE person_t as object external name 'Person' language
java
using SQLData
( ss_no number(9) external name 'ssn',
name varchar2(100) external name 'name',
address varchar2(255) external name 'address'
);

create table employees (employee_id number, emp_det person _t);


insert into employees values (1, person_t(100, 'Scott',
'500 Oracle Parkway'));
insert into tabl ...

Objects Enhancements 10
Accessing SQLJ Object Types in the
Database
• The map between the SQLJ name and the
corresponding Java class is an internal map
populated from the database.
• SQLJ object types can be used as columns of a
base table and attributes of a object type.
• The database SQL engine can access the SQLJ
object's attributes invoke it's methods. For
example:

SQL>
SQL> SELECT
SELECT emp_det.ss_no
emp_det.ss_no FROM
FROM employees;
employees;

• The Oracle9i inheritance feature is supported


for SQLJ objects

Accessing SQLJ Object Types in the Database (continued)


In the above example, when the JDBC queries emp_det column in the employees table , the emp_det
column value is returned as an instance of person
ResultSet rset = stmt.executeQuery ("select emp_det from
employees");
while (rset.next())
Person value = (Person) rset.getObject(1);
To register an SQLJ Object in SQL representation parameter in PL/SQL calls, the new
OracleTypes.JAVA_STRUCT typecode should be specified in
CallableStatement::registerOutParamenter(). That is,
CallableStatement cstmt = conn.prepareCall (...);
cstmt.registerOutParameter (1, OracleTypes.JAVA_STRUCT,
"SCOTT.PERSON_T");
...
cstmt.execute();
Person value = (Person) cstmt.getObject (1);

Objects Enhancements 11
Creating SQLJ Objects

• Each SQLJ Object is the database


representation of Java objects which exist
outside the database.
• To create a SQLJ Object, the Java application
creates the corresponding object and then
INSERTS/UPDATES it to the database.

Creating SQLJ Objects


For example, to create a SQLJ Object of PERSON_T described earlier, the JDBC application creates a
Person object and then it sends it to the database.
Person person = new Person();
person.ssn = 1000;
person.name = "SCOTT";
person.address = "500 Oracle Parkway";
// insert a SQLJ Object "PERSON_T"
PreparedStatement pstmt = conn.prepareStatement ("insert i nto
employees (1, ?)");
pstmt.setObject (1, person);
pstmt.execute ();
The Person Java class has to either implement the SQLData interface or the OraData/OraDataFactory
interface classes.

Objects Enhancements 12
Rules for Inheritance
• The SQLJ type cannot be created under a non
SQLJ object type.
• SQL types cannot be created under SQLJ types
• The USING clause must have the same value for
the SQLJ object type and all its subtypes.
• Two subtypes of a SQLJ object cannot be mapped
to the same external class
• Intermediate classes cannot be skipped in
mapping a SQLJ type hierarchy to a Java class
hierarchy.

REFERENCE
Note: For more information on Inheritance please refer to the lesson on Object Inheritance in
the Objects module

Objects Enhancements 13
Sending SQLJ Objects
• In a typical JDBC application, a Java object that
represents a database object is sent to the
database as one of the following
– a DML bind variable
– a PL/SQL IN parameter
– an object type attribute value
• The Java object can be a instance of SQLData or
OraData
• The Oracle JDBC driver converts the Java object
into the linearized format accepted by the
database SQL engine

Sending SQLJ Objects


The code example below binds a SQLJ Object in a SQL DML -
Person person = ...;
PreparedStatment pstmt = conn.prepareStatment ("insert int o
tabl1 values (1, ?)");
pstmt.setObject (1, person, OracleTypes.JAVA_STRUCT);
pstmt.executeUpdate ();

REFERENCE
Note: For more examples and APIs usage, please refer to Oracle9i Working with Oracle Object
Types, Oracle9i JDBC Developer's Guide and Reference

Objects Enhancements 14
Metadata APIs

• Metadata APIs are used to query the properties of a


datatype
• The metadata APIs of SQLJ Objects are defined in
oracle.sql.StructDescriptor type descriptor
and oracle.jdbc.driver.StructMetaData
classes

Metadata APIs
To obtain the type descriptor, the JDBC applications should use the
oracle.sql.StructDescriptor::createDescriptor factory method as follows --
/**
* Descriptor factory.
*
* Lookup the name in the database, and determine the characteristics
* of this array.
* @param name a String naming the type. (Not necessarily fully qualified)
* @param connection a Connection to a database
*/
public static StructDescriptor createDescriptor(String name, Connection conn)
throws SQLException

StructMetaData provides metadata APIs for SQLJ Object's data fields. StructDescriptor::getMetaData()
returns a instance of
StructMetaData of the type. It contains the following metadata API -

String getAttributeJavaName(int idx) : returns the data field's Java name


Objects Enhancements 15
Data Dictionary Information on SQLJ
Objects

The following views have been added to


support SQLJ object types and objects in the
database:
• {USER|ALL|DBA}_SQLJ_TYPES
• {USER|ALL|DBA}_SQLJ_TYPE_ATTRS
• {USER|ALL|DBA}_SQLJ_TYPE_METHODS

Data Dictionary Information on SQLJ Objects


USER_SQLJ_TYPES : Description of the SQLJ types. It includes information about the
external name, attributes, methods , predefined attributes/methods and whether the type is
incomplete or final or instantiable. It also gives information about the supertype_owner and
super type_name as well as local_attributes and local_methods
USER_SQLJ_TYPE_ ATTRS : Description of attributes of the SQLJ types. It includes
information about the external attribute name, attr_type_owner, attr_type_name
as well as character_set_name and whether the attribute is inherited.
USER_SQLJ_TYPE_ METHODS : Description of methods of the SQLJ type. It includes
information about the external variable names, parameters and results. It also indicates if a
method is final, instantiable, overriding or inherited.

Objects Enhancements 16
Summary

In this lesson, you should have learned about:


• SQLJ Objects
– Creating SQLJ Object type
– Receiving SQLJ Objects
– Creating SQLJ Objects
– Sending SQLJ Objects
– Metadata APIs

Objects Enhancements 17
Appendix A
Terminology

Objects Enhancements 18
Type Inheritance Terminology
Common Supertype – A Type T is said to be the the common supertype
of type s if T is the supertype of every type in S.
Dynamic Type/ Most Specific Type (MST) – the type of value actually in
a slot at a particular moment of runtime execution.
Instance Substitutability – the ability of a slot declared as holding a
value of type T to in fact hold a value of type T or any subtype of type T.
Method overloading – the ability to define multiple methods with the
same method name. At compile time, the compiler chooses the correct
one based on the number, types and order of arguments passed to the
method.
Method Overriding (polymorphism) – the ability to define a new
implementation for a method inherited from a supertype. The only
difference in signature between the inherited and the overriding version of
a method is in the type of self parameter. The overriding method has self
as the subtype, whereas the inherited method has is as the Supertype.
Maximal Supertype (root type) – A type T is said to be a maximal
supertype if there exists no other type that is a supertype of T.
Minimal Common Supertype (MCS) - A type T is said to be the minimal
common supertype of a set of types S if T is a common supertype of S
and further , is a subtype of every common supertype of S
Narrowing – an assignment in which the source is a supertype of the
destination type
REF Substitutability – the ability of a slot declared a holding a value of
REF to type T to in fact hold a value of REF to type T or REF to any
subtype of type T.
Signature – the name of a method and the number, types and order of
the formal parameters of the method. Depending on the context, signature
may or may not include further information, such as the names of the
parameters, return type of the function, purity information and rights
information.
Slot - informally used in this lesson to mean a parameter, variable,
attribute of an object, element of a collection, or expression value – place
where a value can be stored.
Static type/Declared type – the type of value that a type is declared as
able to hold.

Objects Enhancements 19
Type hierarchy – the set of types consisting of a type T and all of
T's subtypes. A type S is more specific than a type T if type s is a
direct or indirect subtype of type T.
Virtual Dispatch – the runtime mechanism used to dynamically
dispatch to the correct routine , given the presence of method
overriding.
Widening – an assignment in which the static type of the source
is more specific than the static type of the target
E.g.. Assigning a leaf_category variable to a category slot. The
validity of this assignment can only be checked at runtime.

Objects Enhancements 20