Title: Modern Database Techniques Part 1: Object Oriented Databases
1Modern Database TechniquesPart 1 Object
Oriented Databases
- 4. Concepts of Object Oriented Databases
2Chapter 4 Overview
- 4.1 Type constructors, complex objects
- 4.2 Classes Type- and Set-View
- 4.3 Relations between Classes, Aggregation
- 4.4 Object Identity
- 4.5 Inheritance
- 4.6 Query Operations
- 4.7 OQL Object Query Language of ODMG
- 4.8 Methods
- 4.9 Integrity
3Requirements for OODBS
- object-oriented perspective
- Complex objects
- Object identity
- Encapsulation
- Types and classes
- Class hierarchies
- Overloading of methods
- optional
- Multiple inheritance
- Database perspective
- Persistance
- Disk-storage organisation
- Concurrent transactions
- Recovery mechanisms
- Query languages
- Database operations
- optional
- Distributed databases
- Version administration
44.1 Type constructors, complex objects
- To be able to store many objects, a set
constructor is necessary - Type of a relational tableSET OF (TUPLE OF (Typ1
A1, . . . , Typn An)) - In OODBS user defined classes can be used besides
basic types. - TUPLE OF corresponds aggregation.
- There are different implementations of the set
operator in different OODBMs
5Overview Type Constructors
- Tuple constructor TUPLE OF
- Combines several components of possibly different
type - Corresponds to aggregation
- Set constructor SET OF
- Many elements of the same type build a set.
- Each element can only be contained once in the
set. - Multi-set constructor BAG OF like set but
- one element can have copies in the bag
- List constructor LIST OF like bag, but
- Sequence is of interest
6Overview Type Constructors (cont.)
- Array constructor ARRAY OF like list, but
- may contain gaps
- index of type long integer
- Dictionary constructor DICTIONARY OF (key,
value) - unordered sequence of (key, value)-pairs
- lookup operation returns value to a given key
- Type constructors are used recursivly
0 1 2 3
Atlanta Paris London
Key Value
A excellent
B very good
C good
D satisfactory
E sufficient
F fail
7Example Type Construction for PersonsGraphical
Representation
Persons
Person
Name
PhoneNumbers
date
Addresses
DOB
Phone Number
string
string
string
string
string
Address
Last Name
FirstName
Second Name
Title
Saluta tion
string
string
string
string
string
string
string
Street
City
State
ZIP
Type
Phone Nr
Type
8Example Type Construction in O2 Persons
- SET OF
- TUPLE OF (
- Name TUPLE OF (
- FirstName STRING, SecondName STRING
- LastName STRING, Title String ),
- Adresses SET OF TUPLE OF ( Street STRING,
City STRING, - ZIP STRING, State STRING, Type String),
- PhoneNumbers LIST OF TUPLE OF (
- PhoneNr STRING, Type STRING),
- DOB DATE)
9ODMG Standard
- ODL (object definition language) for ODMG-types
- extension of IDL (interface definition language)
- similar to C but language independent
- All classes inherit from interface Object that
provides - constructor function (interface ObjectFactory)
- locking information and operation
- identity comparison function same_as(object)
- copy function
- delete function
- Different constructors for collection types
10ODMG Standard (cont.)
- Collections supported by the ODMG-Model
- Set lttgt
- Bag lttgt
- List lttgt
- Array lttgt
- Dictionary ltt, vgt
- where t and v are any types
- Collections supported for objects and for literals
- Atomic types
- long, long long, short
- float, double
- boolean, octet
- char, string
- enum
- type generator
- can only take values listed in declaration
- Structured literals
- date
- time, timestamp
- interval
- user defined with struct
11Example Persons in ODMG-Model
set of objects
- Class Person (extent Persons)attribute NameCl
Name attribute date DOB attribute set
ltAddressgt Addresses attribute list ltPhoneNrgt
PhoneNrs - Class NameClattribute string FirstName
attribute string SecondName attribute string
LastName attribute string Title attribute
string Salutation
no own set of objects
12Example Persons in ODMG-Model
- Class Addressattribute string Country
attribute string City attribute string Street
attribute string ZIP attribute string State
attribute string Type - Class PhoneNrattribute string PhoneNr
attribute string Type
13Type Construction with UML
Tuple Constructor
Set Constructor
complex properties
No dictionary constructor
List or Array Constructor
14Type Constructors in Caché
- Tuple Properties of a class
- Set
- Class automatically gets extent if it inherits
from Persistent - No set-operator for componentsProperty x As set
Of Y not possible - Use list- or array-constructor instead, or
relations - Bag not supported
- List list Of
15Type Constructors in Caché
- Array not directly supported, use dictionary
with integer key values - Dictionary array Of
- Array in Caché is Dictionary in ODMG-Model
!
16Example Persons in Caché
- Class Person Extends (Persistent)Property Name
As NameCl Property DOB As Date Property
Addresses As list Of Address Property
PhoneNumbers As list Of PhoneNumber - Class NameCl Extends (SerialObject)Property
FirstName As String Property SecondName As
String Property LastName As String Property
Title As String Property Salutation As
String
back
17Example Persons in Caché
- Class Address Extends (SerialObject)Property
City As String Property Street As String
Property ZIP As String Property Country As
String Property State As String Property
Type As String - Class PhoneNumber Extends (SerialObject)Propert
y PhoneNr As String Property Type As String
18Type Construction Saving Accounts
- Practice Define the object type of Saving
Accounts as complex type graphically - Different types fixed term, open term, compound
interest - Interest rate may increase every year 2 - 3 -
3.5 - Transactions on account
- Define the same object type in Caché
- What are the consequences of recursive types,
e.g. if Person contains a set Friends of type
Person?
19Type Construction for Saving AccountsGraphical
Representation
Saving Accounts
Saving Account
Transactions
date
string
string
date
float
Interest
Type
AccountNumber
Begin
End
Current Amount
Transaction
Year
Index
int
redundant information
InterestRate
float
Value
float
date
string
string
Date
Amount
Sender
Purpose
20Operations on Complex Types
- Tuple constructor
- Access to components
- Test two tuples on equality
- All collection operators
- Test if collection is empty
- Test if collection contains a certain element
- Access to all elements (iterator)
- Insert, update, or delete element
21Operations on Complex Types (cont.)
- Set constructor
- Set comparisons , ?
- Set operations intersection, union, difference
- Bag constructor
- Number of occurencies of an element
- Set operations intersection, union, difference
- No set comparisons
- List construktor
- Access in sequence of list
- Insert at certain position or after certain
element - Concatenation of lists
22Operations on Complex Types (cont.)
- Array constructor
- Access to elements at certain index
- Dictionary constructor
- Access to elements at certain key
- Test whether certain key is in dictionary
- Bind a value to a certain key (insert)
- Unbind a value from a key (delete)
23Operations on Complex Types in Caché
- Persistent classes (tuple and set constructor)
- Access to components by dot-syntaxp1.Name.FirstNa
me if p1 is a Person object - Test if object exists class methods
Exists(oid) and ExistsId(id) - Retrieve stored objects into memory class
methods Open(oid) and OpenId(id) - Insert or update an element Save()-methodp1.Sa
ve() - Delete an element class methods Delete(oid)
and DeleteID(id) - Iterator to access all objects of a class query
Extent()
24Methods for List- and Array- (Dictionary-)
Collections
Method Purpose Success Failure
List Insert(value) InsertAt(value, index) Array SetAt(value,key) Add value to collection 1 error status
List InsertList(list) Appends list 1 error status
Find(element) Tests whether element is in list index or key ""
GetAt(key) Get value at key value ""
25Methods for List- and Array- (Dictionary-)
Collections (cont.)
Method Purpose Success Failure
RemoveAt(key) Remove object key value at key ""
Count() Count items integer
Clear() Empty collection 1 error status
264.2 Classes Type- and Set-View
- Class has different meanings
- Set of objects belonging together
- Container for all hitherto created objects of the
class - Type construction schema of the objects
- Domain for (abstract) objects
- A state function maps each object to its value,
an element of the domain.
27Concepts for Classes Type-based
type of
- A class defines a complex type
- Objects of the class are not gathered in a
container - This is the situation in programming languages
like C
28Concepts for Classes Set-based
- A class is a container
- Types of the elements are not fixed
29Set-type-based
AND class is container for objects (extent)
class defines a complex type
This is the solution in OODBMSs
304.3 Relations between Classes
- Every class consists of attributes( properties
components) - Their types can be atomic types or classes.
- Class-componentclass-relations implement
relationships between different classes - Distinguish class-subclass-relation ? see 4.5
- Different semantics of component classses
- shared/private component objects
- dependent/independent component objects
- encapsulated/standalone component objects
- unidirectional/mutual component relation
31Shared/Private Component Objects
- Shared component objects
- A component object is component of many objects
- An object can be component of objects of
different classes - MN(1)-relation between component class and class
- Example Branch is shared component of ATM
- Private component objects
- Each component object is component of only one
object - 1N(1)-relation between class and component class
- Example ATM is private component of Branch
32Dependent/Independent Component Objects
- Dependent component objects ?
- ? only exist with object they are component of
- ? are created/deleted with object they are
component of - Shared dependent objects are deleted with last
object they are component of - Example Name is dependent of Person
- Independent component objects ?
- ? can exist without another object
- ? are created and deleted independently
- If you delete a component object, take care of
objects which have it as a component. - Example Branch is independent component of an ATM
33Encapsulated/Standalone Component Objects
- Encapsulated component objects ?
- ? are only accessible by their superior objects.
- ? are always dependent
- Redundancy when used for MN-relations
- Example Name is encapsulated in Person
- Standalone component objects ?
- ? are accessible independently or by the objects
which have them as component. - Example Branch is an standalone class. A branch
is accessible without an ATM- or employee-object
34Unidirectional/Mutual Component Relation
- Unidirectional component relation
- One object is obviously the superior object, the
other the component - No direct way from the component to its superior
object - Example Person ? Name, Car ? Motor
- Mutual component relation
- Each of two objects has the other one as
component. - Implements bidirectional relationship between two
classes - Example Branch ? ATM
35Different Types of Component-Classes
- Practice Decide which is the type for the
following examples of classes and component
classes
shar priv enc aut dep ind dir
Buildings Rooms
Countries Towns
ATMs Currency Orders
Lectures Students
Books Publishers
Books Pages
Folders Files
Parents Children
36Different Types of Component-Classes Solution
- Practice Decide which is the type for the
following examples of classes and component
classes
shar priv enc aut dep ind dir
Buildings Rooms
Countries Towns
ATMs Currency Orders
Lectures Students
Books Publishers
Books Pages
Folders Files
Parents Children
37Different Possibilities for Relationshipsa)
Encapsulated component class
- Complex objects with encapsulated objects of
component class - Suitable for für 11- and 1N-relations
- Redundancy when used for MN-Relations
- Access not symmetrical
- Easy from object to component
- Difficult from component to parent object
- See example Person
- NameCl is encapsulated in Person because it
inherits from SerialObject
38Different Possibilities for Relationships b)
Mutual Component Classes
- Two classes have each other as component
- Can be used for 11-, 1N- and MN-Relations
- Symmetrical access
- System must ensure symmetry
- The relation must not have attributes of its own.
E. g. the examination results of students in the
relation "Students attend Lectures" cannot be
represented
Possibility c) ? later
39Relationships in Caché
- A relationship is a two-way link between an
object of one class and several objects of
another (possibly the same) class. - Relationship types
- Independent (One-to-many).
- Dependent (Parent-to-children).
- Children stored together with parent
- However not encapsulated (children get own object
identifiers) - Classes must be different in this case.
- Indirectly supported One-to-one.
- Not supported Many-to-many, use connection class
40Relationships in Caché (cont.)
- Relationship specified in both class definitions.
- Relationship statementspecialized Property
statement. - One, many, parent, and children define
cardinality of each side of relationship.
41Example Branch and ATM Class Model
0..
1
0..1
1
0..1
Practice Discuss the possibilities to implement
the relation "Branch has ATMs"
1
42Cardinality of Relationships in Caché
- Cardinality number of elements on each side of a
reference. - Describe cardinality in terms of classes.
- FCE.Branch has a parent-to-children relationship
with FCE.ATM. Multiple ATMs belong to each
branch. - Specify cardinality in terms of properties.
- The ATMs property of the FCE.Branch class has
cardinality/type Children. The Branch property of
the FCE.ATM class has cardinality/type Parent.
43OOP Relationship Advantages
- Relationship is a combination of a reference and
a list collection. - Performance degrades as number of objects on
many/children side surpasses 900-1000. - In v4.1, use of CACHETEMP reduces degradation.
- When classes are persistent, relationship
provides referential integrity for object
deletions on one/parent side.
44SQL Relationship Advantages
- When classes are persistent
- Many/children table has foreign key from
one/parent table. - Relationship provides referential integrity for
row deletions on one/parent side.
45Referential Integrity
- For relationships between persistent classes from
A to B - One-to-Many
- Deletion of an object of class A fails as long as
it points to at least one object of class B. - To delete an object of class A, delete the
references to it from objects of class B. - Parent-to-Children
- Deletion of an object of class A deletes all
related objects of class B. - Same is true for rows in tables.
46Demonstration Create a Relationship
- Create two classes.
- Add a property to one class.
- Specify name.
- Use plural name for property with cardinality
many/children, and singular name for property
with cardinality one/parent. - Specify property as a relationship.
- Specify cardinality One, Parent, Many, Children.
- Specify type reference second class.
- Specify name of relationship property to be added
to second class.
47Caché Simulate One-to-One Relationship
- Create one-to-many relationship.
- Change index added on property with cardinality
one (in many class) to unique. - Results
- Prevents object on one side from being
referenced by more than one many object. - Prevents deletion of object on one side.
- But doesnt prevent deletion of object on many
side.
48Using Relationships
- Link objects in two equivalent ways
- Insert many/children into one/parent collection.
- Reference one/parent from many/children object.
- No control over ordering of many/children in
one/parent collection. - To control ordering, use list- or
array-constructor
49Using Relationships (cont.)
- From one/parent side, many/children side is a
collection. To link, either - Insert many/children object into one/parent
objects collection - do branch.ATMs.Insert(ATMOne)
- Insert many object ID directly into one objects
collection, without opening object (only for
one-to-many) - do branch.ATMs.InsertObjectId(atmid)
- Insert new many/children object into one/parent
objects collection - do branch.ATMs.Insert(class(FCE.ATM).New())
50Using Relationships (cont.)
- From many/children side, one/parent side is a
reference. To link, either - Reference one/parent object from many/children
object - set ATMOne.Branch branch
- Set one/parent object ID into many/children
object directly, without opening one/parent
object, using PropertyNameSetObjectId() method. - do ATMOne.BranchSetObjectId(branchid)
51Storing Relationships
- Calling Save() on either one/parent or
many/children triggers save of entire
relationship. - IDs of Children in Parent-to-Children
relationship depend on parent ID. Format
parentIDchildID.
52Implicit Joins
- In a query, using -gt operator on a foreign key
column allows direct references to columns in
foreign table. - Syntax
- table.foreignkey-gtcolumn
- Joins
- -gt operator in SELECT clause creates LEFT OUTER
JOIN. - -gt operator in WHERE clause creates INNER JOIN.
- Transmits efficiency of OO-model to SQL
53Implicit Joins (cont.)
- May be chained.
- select Branch-gtAddress-gtStreet
- Options when querying tables of a
parent-to-children relationship - childtable.parentforeignkey-gtcolumninparenttable
- parenttable.childtable-gtcolumninchildtable
- Works even though childtable is not a column in
parenttable. - Specify childtable without schema.
54Practice Query with -gt Operator
- Write a query with join-conditions, that
- finds the name and street of all branches
- where the phone-number begins with 6
- together with the streets of all ATMs
- Define 2 queries for this task using the -gt
Operator - starting at the Branch-table
- starting at the ATM-table
55Different Possibilities for Relationships c)
Connection Class
- The relation becomes an own class
- Suitable for MN-relations with attributes of
their own - Two 1N-relations from each class to connection
class - In Caché necessary for every many-to-many
relation - Example Employees advise customers
- Different employees advise customers in different
areas like loans, investments, or online banking
0..
advises
Employee
Customer
advisers
0..
subject area
relation with attribute
56Different Possibilities for Relationships c)
Connection Class
- The relation becomes an own class
- Suitable for MN-relations with attributes of
their own - Two 1N-relations from each class to connection
class - In Caché necessary for every many-to-many
relation - Example Employees advise customers
- Many employees advise many customers in different
areas like loans, investments, or online banking
customer
advises
0..
0..
Customercontacts
Employee
Customer
advisers
1
employee
subject area
connection class
attribute
57Summary Different Possibilities to Implement
Relationships in Caché
- Component class Serializable
- Use for unidirectional, private, dependent,
encapsulated components - Component class Persistent
- Use for unidirectional, private, dependent,
standalone components - Relationship one-to-many
- Use for bidirectional, private, independent,
standalone components - Relationship parent-to-children
- Use for bidirectional, private, dependent,
standalone components - Connection class
- Use for bidirectional, shared, independent,
standalone components - Relations with own attributes
584.4 Object Identity Disadvantage of Keys
- No difference between update of an objects value
(content) and its identity (key), e. g. name of a
branch - Problem, when many objects contain the same
component object (e. g. ATMs of a branch) - It is not possible to have different objects with
the same key value. - Queries require inefficient joins.
59Types of Object Identity
- Sum of all values, not practical because
- Values can change
- Object in DB only contains subset of values of
real object - Values of characteristic attributes
- E. g. fingerprint or DNA for real persons
- Difficult to store in DB
- Not applicable for all classes, e. g. chairs in
a lecture room
60Types of Object Identity
- Physical addresses, direct references, pointers
- Pointers point to component-objects
- Pointers point to begin of a list for set
attributes - User defined names of a name domain
- e. g. license numbers of cars
- Automatic keys surrogate keys identifier
attributes (implementation obvious) - Abstract objects (implementation hidden to user)
61Distinguish Objects and Values
- Objects
- Example Branch "City Hall"
- are not printable
- must be created and defined
- carry no information itself
- are described by the values of their attributes
- Values
- Example number 182
- printable
- already exist
- carry information themselves
- describe objects
62Object Identity by Physical Addresses
- Example Identify buildings by their Addresses
- Advantages
- simple implementation
- efficient access of components
- address is not a value of the object
- Disadvantages
- physical data independence violated
- object cannot be moved
- Delete an object. Is physical address reusable?
63Object Identity by Names
- Example Names of persons
- Advantage
- Name can be structured, easy to read first- last
name. - Disadvantages
- can be interpreted as value
- Name can change (e. g. marriage)
- Uniqueness must be checked
- ? keys!
64Object Identity by Surrogate Keys
- Examples AutoNumber in Access, SEQUENCE in
Oracle - Advantages
- Uniqueness guaranteed by system
- cannot be changed
- carries (nearly) no information, is substitute
for object - Disadvantages
- Foreign key constraints must be defined
- Surrugate keys can be interpreted as values.
65Example Saving Accounts with Identifier-Attribut
es
- SET OF (TUPLE OF (Account_Nr IDENTIFIER,
- Type STRING,
- Begin Date,
- End Date
- Account_Holder IDENTIFIER,
-
- Transactions LIST OF(TUPLE OF (Trans_ID
IDENTIFIER, - Amount INT
- ))))
66Saving-Accounts with Identifier-Attributes
Account_Nr Type Begin End Account_Holder Transactions
172963 variable 12. JUN 2002 54355 1 456 1.7.02 2 -63 5.7.02 3
134584 incr. interest 1. AUG 2005 31. JUL 2009 37704 1 456 1.8.05 2 11 31.12.05 3
67Object Identity with Abstract Objects
- Objects are elements of a
- not structured,
- countably infinite,
- abstract set
- with the only information that the elements are
different - Operations on objects
- Create new object
- Delete object
- Test on identity
- You never can print or see an object itself or
its Id
- Abstract objects can be implemented (more or less
well) by - physical addresses
- Names
- Identifier-attributes
68Graphical Representation using State-Boxes
Representation is difficult, since objects cannot
be printed.
object ?19
State of object ?19
Hugo Ross1 May 89
?19
State of object ?2
5 Garden AveSan Francisco, CA 88250
?2
69Abstract Objects
- Advantages
- independent of the implementation
- theoretically sound
- foreign key constraints automatically guaranteed
- Disadvantage
- implemented only in very few real OODBMS
- Two versions
- One infinite set with abstract objects for all
classes - Disjoint domains of abstract objects for each
class
70Saving-Accounts with Abstract Objects and
Disjoint Domains
Account Acc.Nr Type Beg. End Acc.Holder Transactions
?1 172963 variable 12. JUN 2002 ?1 t1 t2 t3
?2 134584 incr. interest 1. AUG 2005 31. JUL 2009 ?1 t4 t5 t6
?1 is not the name of an account holder, not the
key of an account holder, but the whole object
of type customer.
71Operations on Objects
- Create new or delete existing object
- Dereference objects to get their values
- Test on identity o1 o2e. g. father of Peter
father of Susan - Test on shallow equality (of values)
- Test on deep equality (of values)
- Assignment create a reference to an object and
assign it to a variable - Create shallow copy
- Create deep copy
72Comparison of Objects
- Philosophical question When are two objects
identical? - Different comparisons
- Test on identity Do two object-references refer
to the same object? - Test on equality Have two possibly different
objects the same values? - If objects have component objects, compare
whether the component objects are identical
shallow equality - or whether the component objects have the same
values deep equality - Similar questions when copying an object
73Practice Operations on Objects
- Create a new saving-account ?3 by shallow
copying ?1 - Create a new saving-account ?4 by deep copying ?1
- Test on shallow equality of ?1 and ?3?
- Test on deep equality of ?1 und ?4?
- Assign ?1 to variable MyPrimaryAccount
- ?1 MyPrimaryAccount?
- ?1 ?3?
- Why are private component-objects a problem for
shallow copying?
74Practice Solution Operations on Objects
Account Acc.Nr Type Beg. End Acc.Holder Transactions
?1 172963 variable 12. JUN 2002 ?1 t1 t2 t3
?3 172963 variable 12. JUN 2002 ?1 t1 t2 t3
?4 172963 variable 12. JUN 2002 ?2 t7 t8 t9
?2 is a deep copy of ?2, t7 is a deep copy of t1,
75Practice Solution Operations on Objects
- ?1 is shallowly and deeply equal to ?3
- ?1 is deeply equal to ?4 but not shallowly
- ?1 is identical with MyPrimaryAccount
- ?1 is not identical with ?3
- When shallow copying the master object, the copy
gets the same component-object as the original.
Thus the component-object is no longer private.
76Object Identity in Caché
- Every class gets
- New()-method to create objects in memory
- and Save()-method to store them permanently in DB
- Difference between oref
- An oref is a temporary identifier for an object
in memory. - Remove object from memory ? oref is no longer
valid - cannot be printed
- and object ID
- An object ID is a permanent identifier for a
stored object - is automatically created by Save()-method
- never changes
- can be used to locate or delete an object in the
DB - can be printed
- Caché guarantees correspondence of orefs and
object IDs
77Object Identity in Caché (cont.)
- An object Id behaves like an abstract object,
because it - is added as property for every class
- is automatically created when an object is saved
for the first time - cannot be changed by the user
- An object Id behaves different from an abstract
object, because it - only exists for stored objects
- can be printed
- can be used to retrieve a stored object into
memory - carries information whether the object is
encapsulated
78Object Identity in Caché (cont.)
- IDs are class specific ObjectId Id ClassName
- Caché does not provide functions for
- testing shallow equality
- testing deep equality
- If needed these functions must be programmed
- Create a copy of an object with the method
ConstructClone() - deep copy with parameter deep 1
- shallow copy with parameter deep 0
- private component-objects are cloned even with
parameter deep 0 to avoid this, use deep -1
794.5 Inheritance
- Special relation between objects of different
classes "is a", e. g. Customer Miller is a Person - Type inheritance Let T_super and T_sub be
types.T_super is super type of T_sub, T_sub
subtype of T_super - for atomic types if T_sub ? T_supere. g. short
int ? long int - for tupel-types, if T_sub has at least all
components of T_super hat, e. g. Customer and
Person - for set-types, if the element-type of T_sub is
subtype of the element-type of T_super
80Inheritance (cont.)
- Class (set) inheritanceLet C_super und C_sub be
classes - C_sub is more special than C_super, if set of
objects (C_sub) ? set of objects (C_super) - C_sub is subclass, C_super is superclass
- Class and type hierarchy fit together, e. g.
- Class hierarchy Customers ? Persons
- Type hierarchy Customer has all attributes of
Person and additional ones ? Customer is subtype
of Person - DBMS guarantees that every object in class
Customer is in class Person, too. - Define type inheritance, get set inheritance for
free
81Operations for Inheritance
- Specialization
- defines subclasses by inheritance of a superclass
- Not all objects of a superclass must be elements
of one of its subclasses. - Generalization
- combines classes to a collective superclass
- All objects of all subclasses become elements of
the superclass - Often used to define abstract superclasses to
simplify programming, e. g. generalize Branch and
ATM to CashLocation
82Class Tree and Class Graph
- Specialize subclasses ? class tree
animals
vertebrates
invertebrates
birds
mammals
83Class Graph
Person
Name String DOB Date Phone String Email String
- A subclass inherits from more than one superclass
(multiple inheritance)? class graph - Not allowed in all object oriented systems
- Supported by Caché
Addresses
Employee
Customer
Salary Float ESince Date Qualification String
Type String CSince Date Rating String
EmpCust
InterestBonus Float
84Inheritance in ER-Diagrams
Example ER-Diagram of a personal address-book
Name
Phone
Address
Person
o
?
?
Friend
Colleague
RoomNr
WorkPhone
Hobbies
DOB
85Problems
- An object cannot be element of different classes
- Store a colleague who is also your friend? new
class ColleagueFriend necessary - Explosion of combination classesClass with n
subclasses ? 2n - n - 1 combination classes - Objects can't change their class to a subclass
- E. g. colleague becomes friend
- Object must be deleted and created anew
86Inheritance in Caché
- Single or multiple inheritance
- Overriding of properties or methods possible
- To override a property, method argument, or
method return value datatype, new datatype must
be original datatype or its subclass. - To override a method, new method may have more
arguments than original method, but not fewer. - Abstract Classes (objects only in subclasses)
- Syntax Class Subclass Extends SuperclassClass
Subclass Extends (SC1, SC2, )
87Multiple Inheritance in Caché
- Caché supports multiple inheritance.
- Class FCE.ATM Extends (Persistent, Populate,
XML.Adaptor) - In superclass list, order is important.
- First superclass provides class parameters and
members to subclass. - Other superclasses provide class members only.
- Member name conflicts resolved in favor of
superclass listed latest (reverse order of
superclass list).
88Multiple Inheritance in Caché (cont.)
- Additional superclasses can provide
- Complete methods for usage by subclasses.
- Method generators to generate code specific to
subclass. - Empty methods for subclasses to implement.
- Similar to Java's Interface concept.
89Abstract Classes
- Even though a superclass can define properties
and methods, it might not be meant for object
instantiation. - To prevent object instantiation from superclass,
set Abstract attribute to True. - New Class Wizard also allows creation of an
abstract class. - Application code instantiates objects from
concrete (non-abstract) subclasses. - Suitable for
- Generalization, if the superclass only is created
to simplify programming - disjoint partition of a superclass in subclasses
90Discussion of Abstract ClassesExample Person
Class
- Is FCE.Person abstract?
- If yes, application code cant create a Person
object only Customer and Employee objects. - If no, application code can create Persons,
Customers, and Employees. - If abstract, FCE.Person class contains properties
and methods common to all types of persons. - FCE.Customer and FCE.Employee concrete
subclasses.
91Abstract Methods
- Methods of an abstract superclass may optionally
contain code to be inherited. - Setting a superclass methods Abstract attribute
to True shows that method doesnt contain code. - Subclasses should override method and provide
code particular to the subclass. - Application code cant call an abstract method.
- Similar to Private.
92Practice Create Class Graph
- A car dealer not only sells cars but also
journeys. - Create a class graph with UML for the following
classes - Vehicle
- Car
- Truck
- Journey
- Person
- Customer
- Employee
- Sale
934.6 Query Operations
- Class specific operations
- Each class has its own methods.
- A programmer has to implement these methods.
- Disadvantages
- A lot of work to do.
- It is not possible to decide whether set of
operations is complete. - Possibly bad performance.
- Generic Operations
- General database operations provided by the
system - generate class specific operations for every
class - Disadvantage Encapsulation of objects violated
94Generic Query Operations
- Operation Object oriented concept
- Projection Supertype
- Selection Subclass (Subset)
- Join Subtype of two types
- Union Superclass (Superset)
- Intersection Subclass of two classes
- Difference Subclass
- Grouping
- Degrouping
- Object navigation
95Grouping
- Properties of a relation are combined to a new
property. - The new property is a set.
- This can be interpreted as nested relation.
- Degrouping is the opposite operation.
96Example for Grouping Situation before Grouping
ATM Branch Brand SerialNr Address CurrencyBalances
?15 ?3 UBX 123-5 ?102 Euro 3075USD 4788
?16 ?4 UBX 123-7 ?370 Pound 2350USD 5340
?17 ?3 Abam 112675 ?20 Rupees 3900USD 3340
?18 ?4 T.C.C. 45-44-6 ?876 Euro 5150USD 2500
97Example for Grouping Situation after Grouping
by Brand
Brand ATM Branch SerialNr Address CurrencyBalances
UBX ?15 ?3 123-5 ?102 Euro 3075USD 4788
UBX ?16 ?4 123-7 ?370 Pound 2350USD 5340
Abam ?17 ?3 112675 ?20 Rupees 3900USD 3340
T.C.C. ?18 ?4 45-44-6 ?876 Euro 5150USD 2500
98Object Navigation
- If you have a certain object, you can directly
access related objects. - Use dot-syntax.
- Example Print the street names of all ATMs
belonging to the branch in object brchMain - for i11brchMain.ATMs.Count() write !
brchMain.ATMs.GetAt(i) .Address.Street
99Result Sets in Class Hierarchy
- Results of a query are organized in result sets.
- An iterator provided by the result set allows to
step through the elements of the result set. - Three possibilities for the elements of result
sets - Relational operation The elements of the result
set are no objects, the result set is a pure
relation. - Object generating operations Generate new
objects of a new abstract class. - Object conserving operations The elements of the
result sets are the existing objects.
100Example Projection of ATMs to Brand and SerialNr
New-Obj Brand SerialNr
?15 UBX 123-5
?16 UBX 123-7
?17 Abam 112675
?18 T.C.C. 45-44-6
b)
a)
Brand SerialNr
UBX 123-5
UBX 123-7
Abam 112675
T.C.C. 45-44-6
ATM Brand SerialNr
?15 UBX 123-5
?16 UBX 123-7
?17 Abam 112675
?18 T.C.C. 45-44-6
c)
101Degrouping cannot be object conserving
ATM Branch Brand SerialNr Address CurrencyBalances
?15 ?3 UBX 123-5 ?102 Euro 3075
?15? ?3 UBX 123-5 ?102 USD 4788
?16 ?4 UBX 123-7 ?370 Pound 2350
?16? ?4 UBX 123-7 ?370 USD 5340
?17 ?3 Abam 112675 ?20 Rupees 3900
?17? ?3 Abam 112675 ?20 USD 3340
?18 ?4 T.C.C. 45-44-6 ?876 Euro 5150
?18? ?4 T.C.C. 45-44-6 ?876 USD 2500
102Queries in Caché
- Caché uses SQL for queries with extensions for
object oriented access - Implicit join operator "-gt"
- Calculated properties
- Encapsulated components are automatically
unfolded as columns in the corresponding table in
the form ParentTableColumn_ComponentColumn e. g.
Name_FirstName in Person - Advantages
- Well known standard.
- Object view by implicit join operator.
103Defining Class Queries
- Class queries are SELECT queries only, saved with
class. - New Query toolbar button provides wizard to help
build proper SQL statement. - Build complex statement by hand.
- Query can use input parameters, to be supplied at
runtime. For example - where amount gt variable
- Host variables replaced with value of parameter
when query runs.
104Class Queries (cont.)
- You can use relational or object conserving
operations, depending whether the object id is
retrieved by the query. - Code generated when class is compiled.
- ResultSet class provides OOP access to any class
query. - ODBC/JDBC access as Stored Procedure.
- Every persistent class has Extent class query
that returns every ID in extent. - Add EXTENTQUERYSPEC class parameter to specify
additional columns for Extent query.
105Example Class Query
- Retrieve all branches with ATMs in the area with
a certain ZIP code - Query HasATMinZIP(ZIP As String) As
SQLQuery(CONTAINID 1) -
- SELECT ID,Name,Phone,ATM-gtAddress-gtZip
- FROM Branch
- WHERE ATM-gtAddress-gtZip ZIP
106Practice Create Class Query
- Create a class query to find all ATMs that have a
certain currency, e. g. Indian Rupees, in their
CurrencyBalances - currency is a parameter
- Use Implicit join operator ? (for more
information refer to slide Implicit Joins) - You have to use the SQL-Name of the property
CurrencyBalances ATM_CurrencyBalances - The currencies' names are stored in the column
element_key of ATM_CurrencyBalances
107Practice Solution Create Class Query
- ///Find all ATMs with a certain currencyQuery
ATMhasCurrency(currency As String) As
SQLQuery(CONTAINID 1) SELECT ID, Brand,
SerialNumber, Branch FROM ATM WHERE
ATM_CurrencyBalances-gtelement_key
currency
108Using the Predefined Query Extent() Example
Branch
- Create new result setSet rset
class(ResultSet).New ("FCE.BranchExtent") - Execute query Do rset.Execute()
- Step through result setWhile (rset.Next())
set br class(FCE.Branch).OpenId (rset.Data("
ID")) if br.Closes lt PIECE(HOROLOG,",",2)
write br.Name _ " already closed",!
109Class Queries used as Views
- Object conserving operations define virtual
classes - Example Select all ATMs manufactured by UBX
call the class query UBX-ATM. - UBX-ATM is subset of ATM.
- UBX-ATM is automatically updated when ATM is
updated. - Virtual classes correspond to VIEWS in the
relational model. - Object conserving operations avoid explosion of
new classes.
1104.7 OQL Object Query Language of ODMG
- Superset of SQL SELECT
- Differences and enhancements to SQL
- OQL is orthogonal i. e. the result of a query,
operator or function can be used as part of other
queries as long as the types fit. - A dot (".") or an arrow (?") can be used to
access components (implicit join) - Access to methods
- OQL not only can query sets but also other
structures bags, lists, arrays, and dictionaries - Constructor or destructor operations instead of
insert or update respectively.
111Overview of OQL
- Syntax structure of an OQL select-query
- SELECT defines data to be retrieved and
structure of data - FROM specifies collections referenced by the
query and variables to iterate over
those collections - WHERE specifies conditions for selecting
objects - Following slides present examples how to use OQL
- More information
- R.G.G. Cattell. The Object Database Standard
ODMG 2.0. Morgan Kaufmann, San Francisco,
California, 1997. - http//www.openquasar.de/de/components/quasar_pers
istence/oql.html - http//www.eas.asu.edu/cse494db/notes/oodbNotes/o
dmg_oql_mar2002.ppt
112OQL and PATH EXPRESSIONS Navigation Through
Objects
- Path expressions are used to navigate from one
object to another. - Use dot (".") or arrow (?")
- ExampleSELECT p.Name.LastName
- FROM Persons p
- WHERE p?Name?Title "Dr."
- Equivalent FROM p IN Persons
- Persons is extent of persistent class Person
- Result is a multiset of literals type Bag
ltstringgt
DISTINCT
set
Set
113OQLTraversing Attributes and Relationships
- OQL does not allow path expressions to traverse
over multivalued attributes and relationships. - Example not allowedSELECT b.Name,b.ATMs.Address.
StreetFROM b IN BranchWHERE b.ATMs.Address.ZIP
'022456' - Use instead variable a for ATMs
a
, a IN b.ATMs
a
114OQL Extracting from Lists and Arrays
- OQL provides an explicit notation for extracting
the ith element from lists and arrays. - The first element in any indexed collection is
assumed to be 0. - OQL also provides the operations first and last
- Examples
- LIST(a,b,c,d)1 b
- LIST (a,b,c,d)13 LIST (b,c,d)
- FIRST(LIST(a,b,c,d)) a
- LAST(LIST(a,b,c,d)) d
- Convert a list to a setLISTTOSET(LIST(1,2,3,2))
? 1,2,3
115OQL Access Single Elements and Complete Extent
- The ELEMENT-operator converts a set with one
element into this element ELEMENT( SELECT a
FROM a IN ATM WHERE a.SerialNr '543-346-XX') - Select all objects of class Person Persons
116OQL Embedded Queries
- Example SELECT a.Address.StreetFROM a IN
(SELECT a FROM Branch b, a IN b.ATMs WHERE
b.Opens lt '080000'WHERE a.Brand 'T.C.C' - Subquery also possible in SELECT- and WHERE-part
117OQL Structuring Results and Grouping
- GROUP BY provides explicit reference to the
collection of objects within each group or
partition. - Example SELECT STRUCT(Manufacturer,
ATMSerialNr (SELECT p.a.SerialNr FROM p
IN PARTITION))FROM a IN ATMGROUP BY
Manufacturer a.Brand - Result type Struct ltstring, Set ltstringgtgt
118OQL Aggregate Functions
- OQL provides aggregate operators (min, max,
count, sum, avg) over a collection. - Example SELECT STRUCT(BranchObj b,
NrATMs COUNT(b.ATMs))FROM b IN Branch - Result type Struct ltBranch, integergt
119OQL Quantification
- Existential quantification exists x in e1 e2
- TRUE if at least one element of e1 satisfies e2
- Example Select Branches with at least one ATM
from UBX? - SELECT b FROM Branch b WHERE EXISTS a IN
b.ATMS a.Brand 'UBX' - Universal quantification for all x in e1 e2
- TRUE if all elements in e1 satisfy e2
- Example Select Branches with ATMs only from UBX
- SELECT b FROM Branch b WHERE FOR ALL a IN
b.ATMS a.Brand 'UBX'
120PracticeDefine OQL Queries
- Find all ATMs which can supply at least 1000
"Indian Rupees". - Find all managers with the number of employees
they supervise result should be a structure.
Managers supervise at least one employee. - Find serial numbers and streets of all ATMs
belonging to branch "London Westend" which have
at least one currency order that was approved by
"Martin Holmes".
121Practice SolutionDefine OQL Queries
- Find all ATMs which can supply at least 1000
"Indian Rupees". - SELECT a FROM a IN ATM WHERE EXISTS c IN
a.CurrencyBalances c.Currency 'Indian
Rupees' AND c.Balance gt 1000
122Practice SolutionDefine OQL Queries
- Find all managers with the number of employees
they supervise result should be a structure. - SELECT STRUCT ( Manager m, NrSubs
COUNT(m.Subordinates))FROM m IN Employees - WHERE NrSubs gt 0
123Practice SolutionDefine OQL Queries
- Find serial numbers and streets of all ATMs
belonging to branch "London Westend" which have
at least one currency order from Mr. "Hog". - SELECT STRUCT ( SerialNr a.SerialNr, Street
a.Address.Street)FROM a IN ATM, c IN
a.CurrencyOrdersWHERE c.Requestor 'John Hog'
AND - a.Branch 'London Westend'
1244.8 Methods
- perform class specific operations
- are a major difference to pure relational model
- allow to combine structural and operational
development of an application. - can be class methods or instance methods
- can be inherited from superclasses
- Polymorphism Subclass overrides method inherited
from superclass
125Generic Update Methods
Operation Object oriented operation Operation in Caché
Insert Constructor New() classmethod Save() instancem.
Update Access to attribute set obj.property NewVal
Delete Persistent destructor DeleteId(Id)classmethod
Insert Copy Copy ConstructClone(d) d deep or shallow copy
126Where to Code User Specific Methods?In Database
or in Client Application?
- Code methods in database classes, if they
- are used by many different client applications
- access other persistent objects
- query database or perform database operations
- build a unity with the attributes
- Code methods in client application, if they
- perform time consuming calculations
- need a large amount of main memory
- belong to the user interface
- are invoked concurrently by many clients to use
parallel processing on many client computers.
127PracticeClient or Server Side Method
- Where would you code the following methods?
Discuss with your neighbor. Find other examples
for client side and for server side method. - Sum up the amounts of available money for each
currency in all ATMs - A currency exchange transaction is prepared at
home. Calculate the amount of money to be
supplied for a certain requested currency value. - A CAD application stores data of the developed
machines in a database. The engineer can view a
drawing of the machine from different
perspectives, turn it etc. Calculate the drawing.
128Practice SolutionClient or Server Side Method
- Where would you code the following methods?
- Sum up the amounts of available money for each
currency in all ATMs. Server - Prepare currency exchange Calculate the amount
of money to be supplied for a certain requested
currency value. Server - CAD application Calculate the drawing.Client
129Methods in Caché
- Code written in ObjectScript
- allows use of embedded SQL and
- macros.
- or in Caché Basic (similar to Microsoft
VBScript). - Set Language attribute of a class (for all
methods) or individual method(s). - Can be mixed.
- ObjectScript can call Basic.
- Basic can call ObjectScript.
- Both languages compile to same OBJ code.
130Inherited Methods
- Classes that extend other classes inherit their
methods. - For example, new persistent classes inherit
methods of Persistent class.
131Method Signature
arguments
argument name
default value
method name
Method MyMethod (Arg1 As String 'abc', Arg2 As
Numeric) As String set x
argument type
- return type
- result of calculation or
- object or
- status
body
132Method Arguments
- Arguments are private to method.
- Caller is not required to supply all arguments to
a method - do class(Package.Class).Method(1,,3,,4)
- Method must either provide default value for each
argument, or use data or get to check argument. - Method Test(a as String 1, b as String)
as String -
- if 'data(b) code here
133ObjectScript Arguments
- Pass by value.
- Default. Use ByVal in Code Window to make
explicit. - Value passed in for input only.
- Pass by reference.
- Optional. ByRef in Code Window required.
- Inspector uses before name.
- Reference passed in for input and/or output.
- Optionally, use Output in Code Window to document
that argument is for output only. - Use before name in Argument dialog.
134ObjectScript Arguments (cont.)
- Pass by reference/value is for documentation
purposes only. - Shows user how to call method.
- Caller, not signature, determines whether
argument is passed by reference or by value. - Period before argument specifies pass by
reference. - For example
- By value do oref.Method(a,b)
- By reference do oref.Method(.a,.b)
135Objects as Arguments
- Object arguments may be OREFs.
- If method changes properties of object only,
object argument may be passed by value. - Argument inside method references same object as
calling method. - If method changes object argument to reference a
different object, argument must be passed by
reference, in order to return new object to
caller.
136Method Overloading
- Caché doesnt provide method overloading in a way
similar to other languages such as Java. - Cant create multiple methods with the same name
in the same class. - To sim