Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views93 pages

Unit 1

The document provides an overview of Object-Oriented Databases (OODBs), detailing their concepts, advantages, and disadvantages compared to traditional relational databases. It explains key object-oriented principles such as abstraction, encapsulation, inheritance, and polymorphism, and how they apply to OODBs. Additionally, it discusses the structure of objects, object identifiers, and the capabilities of OODBs in modeling real-world entities and handling complex data types.

Uploaded by

Akkal Bista
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views93 pages

Unit 1

The document provides an overview of Object-Oriented Databases (OODBs), detailing their concepts, advantages, and disadvantages compared to traditional relational databases. It explains key object-oriented principles such as abstraction, encapsulation, inheritance, and polymorphism, and how they apply to OODBs. Additionally, it discusses the structure of objects, object identifiers, and the capabilities of OODBs in modeling real-world entities and handling complex data types.

Uploaded by

Akkal Bista
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 93

Unit 1

Object and Object-Relational Databases


Topics covered
• Overview of Object-Oriented concepts;
• Object database extension to SQL;
• The ODMG object model and the Object Definition Language (ODL);
• Object Database Conceptual Design;
• The Object Query Language (OQL)
Overview of Object-Oriented concepts
• Object-oriented databases (OODBs) are a type of database management system (DBMS) that
stores data in the form of objects.
• Objects are similar to the objects used in object-oriented programming languages, and they can
contain both data and methods.
• The four main object-oriented concepts (abstraction, encapsulation, inheritance, and
polymorphism) are also used in OODBs.
• Abstraction:
• Hiding the implementation details of an object and only exposing the essential details to the user.
• In OODBs, abstraction is achieved through the use of classes.
• A class is a blueprint for an object, and it defines the data and methods that the object will have
• Encapsulation:
• Binding together data and methods that operate on that data.
• In OODBs, encapsulation is achieved through the use of objects.
• An object is a concrete instance of a class, and it contains the data and methods defined by the class.
• Inheritance:
• Ability of a new object to acquire the properties and methods of an existing object.
• This allows for code reuse and makes it easier to create new objects.
• In OODBs, inheritance is achieved using subclasses
• Polymorphism:
• Ability of an object to take on different forms.
• This can be achieved through overloading or overriding methods.
• Overloading is the ability to have multiple methods with the same name but different parameters.
• Overriding is the ability to have a subclass method that has the same name and parameters as a method in the parent class.
Contd…
• OODBs offer a number of advantages over traditional
relational databases:
• Better data modeling
• Better code reuse
• Better performance
• OODBs also have some disadvantages:
• Complexity
• Lack of standards
• Limited availability
Object Oriented Database Concepts
• Object oriented databases (OODB) are database that represent data
in the form of objects and classes. An object is real world entity.
• OODB follows the fundamental principles of object oriented
programming.
• The combination of relational model features with object oriented
principles results in an object-oriented database model.
• Object Oriented database model(OODBM) is an alternative
implementation to that of relational model
• Object Oriented Programming + Relational Database Features =
Object Oriented Database Model

5
Object Database Concepts
• The main goal of object oriented databases is to combine the advantages of object
oriented technologies and traditional (relational) databases. They combine object-
oriented features with basic database capabilities.
• i.e., it combines the features of object-oriented programming (OOP) and database
technology, allowing the storage, retrieval, and manipulation of complex data structures.
• On one hand, object orientation helps with improving the modeling of real-world
concepts in the database. On the other hand, basic database capabilities are
needed for ensuring persistence and concurrent sharing of information in
applications.
• OODBMSs allow object-oriented programmers to develop the product, store them
as objects, and replicate or modify existing objects to make new objects within the
OODBMS.
• Object databases store objects rather than data such as integers, strings or real
numbers. Objects are used in object-oriented languages such as Smalltalk, C++,
Java, and others. 6
Concept of Object
An entity in the real world
Object has attribute or what the object has (state)
Object has methods or what the object can do (behavior)
Objects basically consist of
 Attributes - Attributes are data which defines the characteristics of an object. This data may be simple such as
integers, strings, and real numbers or it may be a reference to a complex object.
 Methods - Methods define the behavior of an object and are what was formally called procedures or
functions.
They represent data in the form of object and classes.
ODB follow the fundamental principles of OOP.
OOP + Relational Database features= OODB model
An object has five aspects: identifier, name, lifetime, structure, and creation.
 The object identifier is a unique system-wide identifier (or Object_id). Every object must have an object identifier.
 The name of an object is a human-readable label or identifier assigned to the object.
 The lifetime of an object specifies whether it is a persistent object (that is, a database object) or transient object (objects that is
in the primary memory)
 The structure of an object specifies how the object is constructed by using the type constructors. The structure specifies whether
an object is atomic or not. An atomic object refers to a single object that follows a user-defined type, such as Employee or
Department. If it atomic then it is composed of or dependent on other objects.
Object Oriented Database
Fundamental Features of Object-Oriented Database
• Object and Identity: In an object-oriented database, each real-world entity is represented
by an object. This object has state and behavior. The combination of the current values of
an object’s attributes define the object’s state.
• A set of methods, acting on an object’s state, define the object’s behavior.
• For example, let us consider a real-world entity called ‘student’. A student has states or
properties such as name, rollno, address, date of birth. similarly, the student has
behaviors or methods including attending classes, writing exams, paying fees etc.
State
Name
Rollno
Address
Date of birth
Behavior
Write_exam()
Listen()
Payfee()
Submit_assignment()
9
Fundamental Features of Object Oriented Database
• Object and Identity:
• Each object in the database is identified by a unique object identifier called OID.
• OID is used to uniquely identify and locate objects within the database.
• Object identifiers are typically generated automatically by the database system when objects are created and
can be used to reference or retrieve specific objects.
• The main difference between a key and an object identifier is that a key is used to uniquely identify records
within a table and establish relationships between tables in a relational database, whereas an object identifier is
used to uniquely identify and locate objects within an object-oriented database.
• The value of an OID is not visible to the external user but is used internally by the system to identify each object
uniquely and to create and manage inter-object reference.
• Keys are associated with records or rows, while object identifiers are associated with objects.
• Another difference is, key is unique in a certain relation only. Object identifiers are unique in the whole
database.
• Object identifiers are generated by the database system. Database users have no control over these identifiers.
Keys can be changed by the database users by simply performing a modification operation.
• Properties of OID
1. It is unique
2. It is system generated
3. It is invisible to the user
4. It is not possible to perform operation on OID
5. It is immutable
6. It can not be regenerated 10
Object Structure
• The structure of an object refers to the properties that an object is
made up of. Thus, an object is a real-world entity with certain
attributes that makes up the object structure. Also, an object
encapsulates the data code into a single unit which in turn provides
data abstraction by hiding the implementation details from the user.
• Any object has two properties: state and behavior
• There are two types of objects
• Transient Object : These objects exist during the execution but destroy once
the program terminates.
• Persistent Object : These objects persist and store into database even if
program terminates. Whenever is created, DBMS assigns unique identifier
called as object identity and is abbreviated as OID.
11
Fundamental Features of Object
Oriented Database
• Object and Identity: When using object identifiers, we have to
distinguish two different kinds of object equality. The first one is
identity equality. Identity equality is given, if two objects have the
same object identifier.
• The second one is value equality. Value equality is given, if all the
attribute’s values of two objects are identical.
• Identity equal objects are always value equal. The reverse is not true.

12
Fundamental Features of Object
Oriented
• Encapsulation:
Database
• Encapsulation is the binding together of data and methods that operate on that data.
• In OODBMS, encapsulation is achieved through the use of objects.
• An object is a concrete instance of a class, and it contains the data and methods
defined by the class.
• Encapsulation helps to protect the data in an object from unauthorized access.
• It also helps to make the code more maintainable, as the data and methods are kept
together in a single unit.
• Encapsulation is a key concept in object-oriented programming, and it is one of the
things that makes OODBMSs so powerful.
• Encapsulation in OODBMS has the following benefits:
• It makes it easier to maintain and update the code.
• It protects the data from unauthorized access.
• Example:
• A bank account object might have data fields for the account holder's name, account
number, and balance. It might also have methods for depositing money, withdrawing
money, and transferring money. 13
Fundamental Features of Object Oriented Database
• Inheritance:
• Inheritance is the ability of a new object to acquire the properties and
methods of an existing object.
• In OODBMS, inheritance is achieved through the use of subclasses.
• Inheritance makes it possible to define a class as a subclass of an already existing one
(superclass).
• The subclass inherits all attributes and methods from the superclass and can additionally
define its own attributes and methods.
• Identical parts of the structure of two different classes may be defined only once in a
common superclass. In this, way, less code has to be written.
• A superclass itself also can have a superclass. And this class in turn can have another
superclass. Given this, object-oriented database systems build a hierarchy of their
classes.
• Inheritance in OODBMS has the following benefits:
• It allows for code reuse.
• It makes it easier to create new objects.
14
• It helps to organize the data in a logical way.
Advantages of OODBMS
• Enriched modeling capabilities:
• OODBMSs can model real-world entities more closely than relational databases. This is because they can
represent complex data types, such as objects, inheritance, and polymorphism.
• Extensibility:
• OODBMSs are extensible, which means that new data types and methods can be added easily. This makes
them well-suited for applications that require a lot of flexibility.
• Capable of handling a large variety of data types:
• OODBMSs can handle a wide variety of data types, including objects, strings, numbers, and dates. This makes
them well-suited for applications that require a lot of heterogeneous data.
• Removal of impedance mismatch:
• OODBMSs remove the impedance mismatch between the object-oriented programming model and the
relational database model. This makes it easier to develop applications that use both object-oriented
programming and databases.
• More expressive query language:
• OODBMSs have more expressive query languages than relational databases.
• Navigational access from the object is the most common form of data access in an OODBMS
• This makes it easier to write queries that retrieve complex data.
• Support for schema evolution:
• The tight coupling between data and application in an OODBMS makes schema evolution more feasible.
• Support for long duration transactions:
• OODBMSs use a different protocol to handle the types of long-duration transaction that are common in many
advanced database applications
Disadvantages of OODBMS
• Complexity:
• OODBMSs are more complex than relational databases. This can make them
more difficult to learn and use.
• Lack of universal data model
• There is no universally agreed data model for an OODBMS, and most model lack
of theoretical foundation.
• Performance:
• OODBMSs can be slower than relational databases for some types of queries.
• Lack of experience :
• In comparison to RDBMSs the use of OODBMS is still relatively limited. This
means that we do not yet have the level of experience that we have with
traditional systems. There is a resistance to the acceptance of the technology.
• Security:
• OODBMSs have not traditionally been as secure as relational databases. The user
cannot grant access rights on individual objects or classes. However, this is
improving as OODBMS vendors implement more security features.
Comparison: RDB vs OODB
Object Relational Database ( Oracle)
examples
• Question : use of Type ( Class and object features in relational
database)
create type Employee as object (empID number, empName varchar(20)) not
final;
create table Employee_t of Employee ;
insert into employee_t values(9,'hari’) ;
insert into employee_t values ( new Employee(8,'hariddd’));
select * from employee_t ;
• [ use oracle express edition to run the queries]

19
Question : Implementation of
Inheritances in relational database
create type Person as object (ssn number) not final;
create table Person_t of person;
create type student under person (rollno number) not final;
create table student_t of student;
create type Employee under person (salary number, post varchar(10))
not final;
create table employee_t of Employee;
• Then describe tables, insert values etc

20
Question : Use of member function / method in
relational database
create or replace type Box as object
(l integer,
w integer,
h integer,
member function Volume return integer);

create or replace type body Box as


member function volume return integer is
begin
return l*w*h;
end;
end;

• create table box_table of Box;


• insert into box_table values(10,20,30);
21
• select bb.volume() from box_table bb;
Example: Object as field in an oracle table
create or replace TYPE person_t AS OBJECT ( first_name VARCHAR2(20), last_name VARCHAR2(20), age NUMBER,
MEMBER FUNCTION full_name RETURN VARCHAR2
);
CREATE OR REPLACE TYPE BODY person_t AS
MEMBER FUNCTION full_name RETURN VARCHAR2 IS
BEGIN
RETURN first_name||' '||last_name;
END;
END;
/
create table emp (id int,emp_dtl person_t);
insert into emp values(1,person_t('Hari','Thapa',20));

DECLARE
emp_rec person_t;
BEGIN
SELECT emp_dtl INTO emp_rec FROM emp WHERE ID = 2;
dbms_output.put_line(emp_rec.full_name); 22
END;
User-Defined Types (UDTs) and Complex Structures for Objects
or Constructors
• In ODBs, a complex type may be constructed from other types by nesting of type constructors. The three most basic
constructors are atom, struct (or tuple), and collection.
• Atom: This is the simplest type of constructor, and it is used to represent basic atomic values,
such as integers, real numbers, character strings, Booleans, and any other basic data types
that the system supports directly.
• Struct or Tuple: This constructor is used to represent a collection of values, where the order of
the values is significant. For example, a tuple could be used to represent a person's name,
address, and phone number.
• Collection (or multivalued) type constructors include the set(T), list(T), bag(T), array(T), and dictionary(K,T) type
constructors.
• The main characteristic of a collection type is that its objects or values will be a collection of objects or values of the same type that
may be unordered (such as a set or a bag) or ordered (such as a list or an array).
• Set: set of values of same type with duplication not allowed.
• e.g.: {123,456,789}.
• Multiset or Bag: This constructor is similar to a set, but duplicates are allowed. For example, a bag could be
used to represent a person's favorite colors or a list of the words that a person has used in a document.
• e.g.: {123,456,678,123}
• List: ordered collection of items of the same type with infinite size.
• e.g.: [123,456,678]
• Array: similar to list but fixed size. The array constructor creates a single-dimensional array of elements of the same type. The main
difference between array and list is that a list can have an arbitrary number of elements whereas an array typically has a maximum
size.
• Dictionary constructor creates a collection of two tuples (K, V), where the value of a key K can be used to retrieve the corresponding
23
value V.
Figure 12.4a Illustrating some of the object features of SQL. Using UDTs as types for attributes such as Address
and Phone.

continued on next slide


24
Figure 12.4b Illustrating some of the object features of SQL. Specifying UDT for PERSON_TYPE.

continued on next slide


25
Specifying Type Inheritance
• NOT FINAL:
• The keyword NOT FINAL indicates that subtypes can be created for that type
• UNDER
• The keyword UNDER is used to create a subtype

26
Figure 12.4c Illustrating some of the object features of SQL. Specifying UDTs for STUDENT_TYPE and
EMPLOYEE_TYPE as two subtypes of PERSON_TYPE.

continued on next slide


27
Figure 12.4c (continued) Illustrating some of the object features of SQL. Specifying UDTs for STUDENT_TYPE
and EMPLOYEE_TYPE as two subtypes of PERSON_TYPE.

continued on next slide


28
Specifying Type Inheritance
• Type inheritance rules
• All attributes/operations are inherited
• Order of supertypes in UNDER clause determines inheritance hierarchy
• Instance (object) of a subtype can be used in every context in which a supertype
instance used
• Subtype can redefine any function defined in supertype with the restriction that the
signature is the same.
• When a function is called, the best match is selected based on the types of all
arguments.
• For dynamic linking, the type of the parameters are considered at run time.

29
Specifying Type Inheritance
• This is specified using the keyword UNDER.

30
Object Identifiers Using Reference Types

• Unique system generated object identifiers can be created via the reference
type using the keyword REF.
• For example, the following statement
REF IS SYSTEM GENERATED
• Indicates that whenever a new PERSON_TYPE is created, the system will assign it a
unique system generated identifier.
• It is also possible not to have a system generated object identifier and use the
traditional keys of the basic relational model if required.
• In general, the user can specify that system generated object identifiers for the
individual rows in a table should be created. By using the syntax:
REF IS <OID_ATTRIBUTE> <VALUE_GENERATED_METHOD>;

31
Object Identifiers Using Reference Types

• The user declares that the attribute named <OID_ATTRIBUTE> will be used to
identify individual tuples in the table.
• The option for <VALUE_GENERATED_METHOD> are SYSTEM GENERATED or
DERIVED.
• In the former case, the system will automatically generate a unique identifier
for each tuple.
• In the later case, the traditional method of using the user-provided primary
key value to identify tuples is applied.

32
Figure 12.4d Illustrating some of the object features of SQL. Creating tables based on some of the UDTs, and
illustrating table inheritance.

continued on next slide


33
Specifying Relationships via
Reference
• Component attribute of one tuple may be a reference (specified using
the key-word REF) to a tuple of another(or possibly the same) table.
• The keyword SCOPE specifies the name of the
table whose tuples can be referenced by the
reference attribute.
• It is similar to a foreign key, except that the
system generated OID is used rather than the
primary key.

34
Figure 12.4e Illustrating some of the object features of SQL. Specifying relationships using REF and SCOPE.

35
Encapsulation of Operations

• In SQL, a user defined data type can have its own behavioral specification by
specifying methods in addition to the attributes. The general form of a UDT
specification with methods is as follows:

• CREATE TYPE <TYPE-NAME> (


• <List of component attributes and their types>
• <declaration of functions (methods)>
• );
• In general, a UDT can have a number of user defined functions associated with
it. The syntax is:
INSTANCE METHOD <NAME> (<ARGUMENT_LIST> RETURNS <RETURN TYPE>;

36
Summary of SQL Object
Extensions
• UDT to specify complex types
• INSTANTIABLE specifies if UDT can be used to create tables;
NOT FINAL specifies if UDT can be inherited by a subtype
• REF for specifying object identity and inter-object
references
• Encapsulation of operations in UDT
• Keyword UNDER to specify type inheritance and
table inheritance

37
Object Database Management Group (ODMG)
• It is an object-oriented database standard that was developed in the early 1990s.
• The ODMG object model is a collection of concepts that define how objects are
represented in an object database.
• These concepts include objects, classes, interfaces, properties, relationships, and
operations.
• ODMG uses an object-oriented data model, which is a natural fit for object-oriented
applications.
• A consortium of ODB vendors and users, called ODMG (Object Data Management Group), proposed a
standard that is known as the ODMG-93 or ODMG 1.0 standard.
• This was revised into ODMG 2.0 and later to ODMG 3.0.
• The standard is made up of several parts, including the object model, the object definition language
(ODL), the object query language (OQL) and the bindings to object –oriented programming languages.
• The ODMG object definition language (ODL) is a language that is used to define the
object model for an object database. ODL is based on the C++ programming
language.
• The ODMG object query language (OQL) is a language that is used to query object
databases. OQL is based on the SQL query language.
The Object Model of ODMG
• Provides a standard model for object databases
• Supports object definition via ODL
• Supports object querying via OQL
• Supports a variety of data types and type constructors
ODMG Objects and Literals
• The basic building blocks of the object model are
• Objects
• Literals
• An object has four characteristics
1. Identifier: unique system-wide identifier
2. Name: unique within a particular database and/or program; it is optional
3. Lifetime: persistent vs. transient
4. Structure: specifies how object is constructed by the type constructor and whether
it is an atomic object
ODMG OM - Basic Modeling Primitives
Basic modeling primitives are object and literal.
Only an object has a unique identifier.
All objects of given type exhibit common behavior and state. A type is
itself an object.
 The state of an object is defined by the values of its
properties.
Behavior defined by set of operations that can be performed on or by
object.
Property may be either an attribute of object or relationship between
object and one or more other objects.
Relationships are used to connect objects together. Relationships can be
either one-to-one, one-to-many, or many-to-many.
ODMG Literals
• A literal has a current value but not an identifier
• Three types of literals
1. atomic: predefined; basic data type values (e.g., short, float,
boolean, char)
2. structured: values that are constructed by type constructors (e.g., date,
struct variables)
3. collection: a collection (e.g., array) of values or objects
ODMG Interface Definition:
An Example
• Note: interface is ODMG’s keyword for class/type

interface Date:Object {
enum weekday{sun,mon,tue,wed,thu,fri,sat};
enum Month{jan,feb,mar,…,dec};
unsigned short year();
unsigned short month();
unsigned short day();

boolean is_equal(in Date other_date);
};

Slide 21- 43
Object Inheritance Hierarchy

Slide 21- 44
Atomic Objects
• Atomic objects are user-defined objects and are defined via keyword class
• An example:
class Employee (extent all_emplyees key ssn) {
attribute string name;
attribute string ssn;
attribute short age;
relationship Dept works_for;
void reassign(in string new_name);
}

Slide 21- 45
Class Extents
• An ODMG object can have an extent defined via a
class declaration
• Each extent is given a name and will contain all
persistent objects of that class
• For Employee class, for example, the extent is called
all_employees
• This is similar to creating an object of type
Set<Employee> and making it persistent

Slide 21- 46
Class Key
• A class key consists of one or more unique attributes
• For the Employee class, the key is ssn
• Thus each employee is expected to have a unique ssn
• Keys can be composite, e.g.,
• (key dnumber, dname)

Slide 21- 47
Object Factory
• An object factory is used to generate individual objects via its
operations
• An example:
interface ObjectFactory {
Object new ();
};
• new() returns new objects with an object_id

• One can create their own factory interface by inheriting the above
interface
Slide 21- 48
Interface and Class Definition
• ODMG supports two concepts for specifying object types:
• Interface
• Class
• There are similarities and differences between interfaces and classes
• Both have behaviors (operations) and state (attributes and
relationships)

Slide 21- 49
ODMG Interface
• An interface is a specification of the abstract behavior
of an object type
• State properties of an interface (i.e., its attributes and
relationships) cannot be inherited from
• Objects cannot be instantiated from an interface

Slide 21- 50
ODMG Class
• A class is a specification of abstract behavior and state
of an object type
• A class is Instantiable
• Supports “extends” inheritance to allow both state and
behavior inheritance among classes
• Multiple inheritance via “extends” is not allowed

Slide 21- 51
Object Definition Language (ODL)
• ODL supports semantics constructs of ODMG
• ODL is independent of any programming language
• ODL is used to create object specification (classes and interfaces)
• ODL is not used for database manipulation
• It is a language used to define the structure of an object-oriented
database.
• ODL is based on the C++ programming language.
• ODL is a portable language. This means that you can use it to define the
structure of object-oriented databases that can be used on different
platforms.
• ODL is powerful and flexible i.e., ODL allows you to define complex object
structures, and it provides a way to enforce data integrity constraints.
• ODL is not a full programming language, but rather a definition language for object
specifications.
• ODL should be programming language independent.
Figure 12.9a An example of a database schema. Graphical notation for representing ODL schemas.

continued on next slide


54
ODL Example
• ODL Examples: A Simple Class
class Degree {
attribute string college;
attribute string degree;
attribute string year;
};
• ODL Examples : A Class With Key and Extent
class Person (extent persons key ssn) {
attribute struct Pname {string fname …} name;
attribute string ssn;
attribute date birthdate;

short age();
}
ODL Examples: A Class With Relationships
• Note extends (inheritance) relationship
• Also note “inverse” relationship

Class Faculty extends Person (extent faculty) {


attribute string rank;
attribute float salary;
attribute string phone;

relationship Dept works_in inverse Dept::has_faculty;
relationship set<GradStu> advises inverse GradStu::advisor;
void give_raise (in float raise);
void promote (in string new_rank);
};
56
Interface Inheritance via “:” – An
Example
interface Shape {
attribute struct point {…} reference_point;
float perimeter ();

};

class Triangle: Shape (extent triangles) {


attribute short side_1;
attribute short side_2;

};
57
An example of a database schema. A graphical object database schema for part of the
UNIVERSITY database (GRADE and DEGREE classes are not shown).
An illustration of interface inheritance via “:”.
Graphical schema representation.
Figure 12.11b An illustration of interface inheritance via “:”. Corresponding interface and class
definitions in ODL.
Atomic (User-Defined) Objects
• Atomic Objects are specified using keyword class in ODL.
• In the object model, any user defined object that is not a collection object is called an
atomic object.
• Attribute is property that describes some aspect of an object. Attributes have values that
are stored within the object. Attribute values can also be Object_ids of their objects.
• Relationship is a property that specifies that two objects in the database are related. In
the object model of ODMG, only binary relationships are explicitly represented, and each
binary relationship is represented by a pair of inverse references specified via the
keyword relationship.
• Operation signature: Each object type can have a number of operation signatures, which
specify the operation name, its signature type, and its return type, if applicable.
• Operation names are unique within each object type, but they can be overloaded by
having the same operation name appear in distinct object type.
• The operation signature can also specify the names of exceptions that can occur during
operation execution 63
Figure 12.7 The attributes, relationships, and operations in a class definition.
Object Query Language
• OQL is a query language proposed for ODMG object model
• OQL works closely with programming languages such as C++
• OQL’s syntax is similar to SQL with additional features for objects
• Provides declarative access to object database using SQL-like syntax.
• Object Query Language (OQL) is a query language standard for object-
oriented databases modeled after SQL.

Slide 21- 65
Simple OQL Queries
• Basic syntax: select…from…where…
• SELECT d.name
• FROM d in departments
• WHERE d.college = ‘Engineering’;
• An entry point to the database is needed for each query
• An extent name (e.g., departments in the above example) may
serve as an entry point

Slide 21- 66
Iterator Variables
• Iterator variables are defined whenever a collection is referenced in
an OQL query
• Iterator d in the previous example serves as an iterator and ranges
over each object in the collection
• Syntactical options for specifying an iterator:
• d in departments
• departments d
• departments as d

Slide 21- 67
Data Type of Query Results
• The data type of a query result can be any type defined in the ODMG
model
• A query does not have to follow the select…from…where…
format
• A persistent name on its own can serve as a query whose result is a
reference to the persistent object. For example,
• The query Q1: departments;
• returns a reference to the collection of all persistent DEPARTMENT objects, whose type is
set. (set<Departments>)
Path Expressions
• A path expression is used to specify a path to attributes and objects
in an entry point
• A path expression starts at a persistent object name (or its iterator
variable)
• The name will be followed by zero or more dot connected relationship
or attribute names
• E.g., departments.chair;
• Attributes, relationships, and operation names (methods) can be used
interchangeably within the path expressions
Views as Named Objects
• The define keyword in OQL is used to specify an identifier for a
named query
• The name should be unique; if not, the results will replace an existing
named query
• Once a query definition is created, it will persist until deleted or
redefined
• A view definition can include parameters
An Example of OQL View
• A view to include students in a department who have a minor:
define has_minor(dept_name) as
select s
from s in students
where s.minor_in.dname=dept_name

• has_minor can now be used in queries


• E.g., has_minor(CSE);
Single Elements from Collections
• An OQL query returns a collection
• OQL’s element operator can be used to return a single element from a singleton
collection that contains one element:

element (select d from d in departments


where d.dname = ‘Software Engineering’);
• If d is empty or has more than one elements, an exception is raised

• If the query returns more than one record, the collect operator can be used to fetch
the records.
• The collect operator returns a collection of all the records that are returned by the
query.
collect (select d from d in departments
where d.dname = 'Software Engineering’);
Collection Operators
• OQL supports a number of aggregate operators that can be applied to
query results
• The aggregate operators and operate over a collection and include
• min, max, count, sum, avg
• count returns an integer; others return the same type as the
collection type
An Example of an OQL
Aggregate Operator
• To compute the average GPA of all seniors majoring in Business:

avg (select s.gpa from s in students


where s.class = ‘senior’ and
s.majors_in.dname =‘Business’);
Membership and Quantification
• OQL provides membership and quantification operators:
• The membership and quantification expressions return a Boolean
type—that is, true or false.
• (e in c) is true if e is in the collection c
• (for all e in c: b) is true if all e elements of collection c satisfy b
• (exists e in c: b) is true if at least one e in collection c satisfies b
An Example of Membership
• To retrieve the names of all students who completed CS101:

select s.name.fname s.name.lname


from s in students
where 'CS101' in
(select c.name
from c
in s.completed_sections.section.of_course);

Explanation of in clause :
In clause specifies the subquery that is used to evaluate the condition in the where clause.
The subquery here retrieves the names of all courses that the student has completed.

Above query retrieve the first name and last name of all students who have completed a section of the course
CS101.
Ordered Collections
• Collections that are lists or arrays allow retrieving their first, last, and
ith elements
• OQL provides additional operators for extracting a sub-collection and
concatenating two lists
• OQL also provides operators for ordering the results
An Example of Ordered Operation
• To retrieve the last name of the faculty member who earns the
highest salary:

first (select struct


(faculty: f.name.lastname,
salary f.salary)
from f in faculty
ordered by f.salary desc);
Grouping Operator
• OQL also supports a grouping operator called group by
• Provides explicit reference to the collection of objects within each group or partition
• For example, retrieves the number of majors in each department.

select struct( dept_name, number_of_majors: count


(partition)
)
from S in STUDENTS
group by dept_name: S.Majors_in.Dname;

• In this query, the students are grouped into the same partition (group) if they have
the same major; i.e., the same value for S.Majors_in.Dname
Having clause
• Used to filter partitioned sets
• E.g., To retrieve average GPA of majors in each
department having > 100 majors:
select deptname, avg_gpa:
avg (select p.s.gpa from p in partition)
from s in students
group by deptname: s.majors_in.dname
having count (partition) > 100
Object Database Conceptual Design

• Object Database (ODB) vs. Relational Database (RDB)


• Relationships are handled differently
• Inheritance is handled differently
• Operations in OBD are expressed early on since they are a part of the class
specification
Relationships: ODB vs. RDB (1)
• Relationships in ODB:
• relationships are handled by reference attributes that include OIDs of related
objects
• single and collection of references are allowed
• references for binary relationships can be expressed in single direction or
both directions via inverse operator
• Relationships in RDB:
• Relationships among tuples are specified by attributes with matching values
(via foreign keys)
• Foreign keys are single-valued
• M:N relationships must be presented via a separate relation (table)
Inheritance Relationship in ODB vs. RDB
• Inheritance structures are built in ODB (and achieved via “:”
and extends operators)
• RDB has no built-in support for inheritance relationships
There are several options for mapping inheritance relationships in an RDB: Student (RegNo, name)
Table per class hierarchy: PosGrad (RegNo, supervisor)
This strategy creates a separate table for each class in the inheritance hierarchy. UnderGrad (RegNo, points)
The tables are linked together using foreign keys.
This strategy is the most flexible, but it can also be the most complex and inefficient.
Table per subclass:
This strategy creates a separate table for each subclass in the inheritance hierarchy.
The attributes in the superclass are duplicated in all subclasses. PosGrad (RegNo, name, supervisor)
The tables are linked together using foreign keys. UnderGrad (RegNo, name, points)
This method is most preferred when inheritance is disjoint and complete, e.g. every student is either PosGrad or
UnderGrad and nobody is both.
This strategy is less flexible than table per class hierarchy, but it can be more efficient.
Only the superclass is mapped to a table:
The attributes in the subclasses are taken to the superclass. Student (Regno, name, supervisor, points)
This method will introduce null values
This strategy is the least flexible, but it can be the most efficient.
Early Specification of Operations
• Another major difference between ODB and RDB is the
specification of operations
• ODB:
• Operations specified during design (as part of class specification)
• RDB:
• Operations specification may be delayed until implementation
Mapping EER Schemas to ODB Schemas

• Mapping EER schemas into ODB schemas is relatively simple


especially since ODB schemas provide support for inheritance
relationships
• Once mapping has been completed, operations must be added to
ODB schemas since EER schemas do not include an specification of
operations
Differences between Conceptual Design of ODB
and RDB
ODB Design RDB Design

Relationships are handled by relationship properties or


Relationships among tuples (records) are specified by attributes
reference attributes that include OID(s) of the related
with matching values.
objects.

Relationships are limited to being single-valued in each record


Relationships can be represented using single references or
because multivalued attributes are not permitted in the basic
collections of references.
relational model.

Mapping binary relationships that contain attributes is not


M:N relationships must be represented not directly but as a
straightforward, and it may be preferable to create a
separate relation (table).
separate class to represent the relationship.

Inheritance is handled using the inheritance constructs such No built-in construct exists for inheritance in the basic relational
as derived (:) and extends. model.

Operations are part of the class specifications and need to


Operations may be delayed until the implementation phase.
be specified early on in the design.

The object model mandates the predefinition of a set of The relational model does not mandate the database designers to
valid behaviors or operations. predefine a set of valid behaviors or operations.
86
Mapping EER to ODB Schemas
Step 1
• Create an ODL class for each EER entity type or subclass
• Multi-valued attributes are declared by sets, bags or lists constructors
• If the values of the multivalued attribute for an object should be ordered, the list
constructor is chosen;
• if duplicates are allowed, the bag constructor should be chosen;
• otherwise, the set constructor is chosen.
• Composite attributes are mapped into a tuple constructor (by using a struct
declaration in ODL).
• Declare an extent for each class and specify any key attributes as keys of the
extent.
Mapping EER to ODB Schemas
Step 2
• Add relationship properties or reference attributes for each binary
relationship into the ODL classes participating in the relationship
• Relationship cardinality: single-valued for 1:1 and N:1 directions; collection
types (set-valued or list valued) for 1:N and M:N directions
• Relationship attributes: create via tuple constructors (struct)
Mapping EER to ODB Schemas
Step 3
• Add appropriate operations for each class
• Operations are not available from the EER schemas; original requirements
must be reviewed
• Corresponding constructor and destructor operations must also be added
Mapping EER to ODB Schemas
Step 4
• Specify inheritance relationships via extends clause
• An ODL class that corresponds to a sub-class in the EER schema inherits the
types and methods of its super-class in the ODL schemas
• Other attributes of a sub-class are added by following Steps 1-3
• i.e., its specific (non-inherited) attributes, relationship references, and operations are
specified.
Mapping EER to ODB Schemas
Step 5
• Map weak entity types in the same way as regular entities. However, there are
a few key differences.
• The weak entity type is represented by a class. The class will have all
the attributes of the weak entity type, as well as a reference attribute to
the owner entity type.
• The reference attribute is a single-valued reference attribute. This
means that each weak entity object can only have one owner entity object.
• The weak entity type is not self-identifying. This means that the
weak entity type does not have its own primary key. The primary key of the
weak entity type is the primary key of the owner entity type plus the
identifying attributes of the weak entity type.
• Weak entities that do not participate in any relationships may alternatively be presented as
composite multi-valued attribute of the owner entity type by using the set<struct> or
list<struct> constructors.
Mapping EER to ODB Schemas
Step 6
• Map categories (union types) to ODL
• The process is not straightforward
• May follow the same mapping used for
EER-to-relational mapping: For example, Car booking, Car owner can be a
• Declare a class to represent the category
person, a bank (holds a possession on a Car) or
• Define 1:1 relationships between the
category and each of its super-classes a company.
Category (sub class) → Owner is a subset of the
union of the three super classes → Company, Bank,
and Person.
A Category member must exist in at least one of its
super classes.
Mapping EER to ODB Schemas
Step 7
• Map n-ary relationships whose degree is greater than 2
• Each relationship is mapped into a separate class with appropriate reference to each
participating class
• To map an n-ary relationship to ODL, we can follow this approach:
• Create a separate class to represent the n-ary relationship.
• Add reference attributes to the class for each participating class.
• Define the cardinality of the relationship between the n-ary relationship class and each
participating class.

class Prescribes
{
/* Define following relationship in ODL format */
patient : Patient;
doctor : Doctor;
medicine : Medicine;
}

You might also like