chapter 20 - 21 bases de datos orientadas a objetos copyright © 2004 pearson education, inc

59

Upload: pancho-baria

Post on 28-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc
Page 2: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Chapter 20 - 21 Bases de Datos Orientadas a

Objetos

Copyright © 2004 Pearson Education, Inc.

Page 3: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-3

Contenido

20.1 Conceptos fundamentales20.2 O-O Identidad, Estructura y Tipo de los

Constructores de Objetos20.3 Encapsulación de Operaciones, Métodos

y Persistencia20.4 Tipo y Jerarquía de Clases y Herencia 20.5 Objectos Complejos20.6 Otros Conceptos O-O21 Object Query Language (OQL)20.7 Resumen y Estado Actual

Page 4: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-4

Introducción

Modelos de Datos Tradicionales : Jerárquico, Red (desde mid-60’s), Relacional (since 1970 y commercialmente desde 1982)

Modelos de Datos (OO) desde mid-90’sRazones para creación de OODB

– Necesidad para aplicaciones más complejas– Necesidad para características adicionales de modelado de datos– Incremento del uso de OOLP

OODB Commerciales – algunos en 1990’s, pero no tuvieron mucho impacto.

Page 5: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-5

Historia de Modelos y Sistemas OO

Languajes: – Simula (1960’s), Smalltalk (1970’s), C++ (late 1980’s),

Java (1990’s)Sistemas Experimentales:

– Orion at MCC, IRIS at HP labs, Open-OODB at T.I., ODE at ATT Bell labs, Postgres - Montage - Illustra at UC/B, Encore/Observer at Brown

OODB Comerciales: Ontos, Gemstone, O2 , Objectivity, Objectstore ,

Versant

Page 6: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-6

Object-Oriented Conceptos(1)

ARGUMENTO PRINCIPAL: OODB tratan de mantener una correspondencia directa entre el mundo real y la BD de objetos – ya que estos no pierden su integridad e identidad y

pueden ser fácilmente identificados y operados Objeto: Dos componentes: estado (valor) y

comportamiento (operaciones). – Similar a una variable de programa en un lenguaje de

programación , – Excepto que típicamente tienen una estructura de datos

compleja también como operaciones específicas definidas por el programador

Page 7: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-7

Object-Oriented Conceptos (2)

En OODB, los objetos pueden tener una estructura de arbitraria complejidad para contener toda la información necesaria de los mismos.

En contraste, en SBD tradicionales, la información acerca de objetos complejos es a menudo diseminada sobre muchas relaciones llevando a la pérdida directa de correspondencia entre el mundo real y su instancia correspondiente en la BD

Page 8: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-8

Object-Oriented Concepts (3)

Algunos modelos OO insisten que todas las operaciones que un usuario puede aplicar a un objeto tienen que estar predefinidas .Esto fuerza a una completa encapsulación de los objetos

Para fomentar la encapsulación, una operación está definida en dos partes:

1. signature o interface de la operación, especifica el nombre y los argumentos de la operación

2. método o cuerpo, especifica la implementación de la operación.

Page 9: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-9

Object-Oriented Concepts (4)

Las operaciones pueden ser invocadas pasando un mensaje a un objeto, el cual incluye el nombre y los parámetros de la operación. El objeto entonces ejecuta el método pra la operación.

La encapsulación permite la modificación de la estructura interna de un objeto, también como la implementación de sus operaciones, sin la necesidad de perturbar los programas externos que invocan esas operaciones.

Page 10: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-10

Overview of Object-Oriented Concepts (5)

Algunos sistemas OO suministran capacidades para tratar con múltiples versiones del mismo objeto (característica esencial en diseño e ingeniería de aplicaciones). – Por ejemplo, una versión antigua de un objeto que

representa un diseño probado y verificado debe ser retenida hasta que la nueva versión sea probada y verificada:

– muy crucial para diseños en control de procesos de manufactura, arquitectura , sistemas de software …..

Page 11: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-11

Object-Oriented Concepts (6)

Polimorfismo del operador: Se refiere a la habilidad de una operación para ser aplicada sobre diferentes tipos de objetos; en tal situación, un nombre de una operación puede referirse a algunas distintas implementaciones, dependiendo del tipo de objetos al que esta es aplicada.

Esta característica es también llamada operator overloading (sobrecarga)

Page 12: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-12

Identidad del Objeto

Identidad Unica: Un sistema de BD suministra una identidad única a cada objeto independiente almacenado en la BD. Esta identidad única es típicamente implementada vía un único identificador de objeto (OID) generado por el sistema.

La propiedad principal de un OID es que es immutable; esto es, el valor del OID de un objeto particular no debe variar. Esto preserva la identidad del objeto del mundo real siendo representado.

Page 13: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-13

Tipos de Constructores

Tipos de Constructores: En OODB, el estado (valor actual) de un objeto complejo pueda estar construido a partir de otros objetos (u otros valores) usando ciertos constructores tipo.

Los tres constructores más básicos atom, tuple, and set. Otros constructores comúnmente usados son incluyen list, bag, and array.

El constructor atom es usado para representar todos los valores atómicos básicos, tales como, enteros, reales, cadenas, boleanos.

Page 14: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-14

Ejemplo 1, un posible estado de una BD relacional correspondiente al esquema COMPANY

Page 15: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-15

Ejemplo 1 (cont.):

Page 16: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-16

Example 1 (cont.)

Page 17: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-17

Identidad, Estructura, y Tipos de Constructores de ObjetosExample 1 (cont.)

Usamos i1, i2, i3, . . . para identificadores de objetos únicos generados por el sistema. Considere los siguientes objetos:

o1 = (i1, atom, ‘Houston’)

o2 = (i2, atom, ‘Bellaire’)

o3 = (i3, atom, ‘Sugarland’)o4 = (i4, atom, 5)

o5 = (i5, atom, ‘Research’)

o6 = (i6, atom, ‘1988-05-22’)

o7 = (i7, set, {i1, i2, i3})

Objetos o1 al o6 representan valores atómicos .

o7 es un object tipo set que representa el conjunto de ubicaciones para el departmento 5;– el conjunto se refiere a los objetos

atómicos con valores {‘Houston’, ‘Bellaire’, ‘Sugarland’}.

Page 18: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-18

Identidad, Estructura, y Tipos de Constructores de ObjetosExample 1(cont.)

o8 = (i8, tuple, <dname:i5, dnumber:i4, mgr:i9, locations:i7, employees:i10, projects:i11>)o9 = (i9, tuple, <manager:i12, manager_start_date:i6>)o10 = (i10, set, {i12, i13, i14})o11 = (i11, set {i15, i16, i17})o12 = (i12, tuple, <fname:i18, minit:i19, lname:i20, ssn:i21, . . ., salary:i26, supervi sor:i27, dept:i8>). . .

Object 8 es un objeto tipo tuple que representa el departmento, y tiene los atributos DNAME, DNUMBER, MGR, LOCATIONS, EMPLOYEES Y PROJECTS.

Page 19: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-19

Identidad, Estructura, y Tipos de Constructores de Objetos

Example 2:Muestra la diferencia entre las dos definiciones para comparar estados de los objetos por igualdad .

o1 = (i1, tuple, <a1:i4, a2:i6>)o2 = (i2, tuple, <a1:i5, a2:i6>)o3 = (i3, tuple, <a1:i4, a2:i6>)o4 = (i4, atom, 10)o5 = (i5, atom, 10)o6 = (i6, atom, 20)

Los objetos o1 y o2 tienen estados iguales, porque sus estados a nivel atómico son los mismos pero sus valores son alcanzados a traves de distintos objetos o4 and o5.

Sin embargo los estados de los objetos o1 and o3 son idénticos, aunque los objetos por ellos mismos no lo son porque ellos tienen diferentes OIDs.

Similarmente, aunque los estados de o4 and o5 son idénticos, los objetos actuales o4 and o5 son iguales pero no idénticos, porque ellos tienen distintos OIDs.

Page 20: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-20

Identidad, Estructura, y Tipos de Constructores de Objetos

Figure 20.1 Representation of a DEPARTMENT complex object as a graph

Page 21: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-21

OODBMS

OODBMS están fuertemente acoplados con un OOLP.OOLP is used para especificar las implementaciones de los

mètodos así como los programas de aplicación.ODMG object model sobre el cual ODL Y OQL (object

definición y query languajes) están basadosODL incorpora la definición de los constructores de objetos.

Los constructores de objetos pueden ser usados para describir las estructuras de datos para un esquema de una OODB

OQL es el lenguaje de consulta diseñado para trabajar muy cercanamente con OOLP.

Page 22: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-22

Tipos de Constructores de Objetos (ODL)

Specifying the object types Employee, Date, and Department using type constructors

Page 23: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-23

Encapsulation of Operations, Methods, and Persistence (1)

EncapsulaciónEs una de las principales características de lenguajes y

sistemas OO.Relacionado a los conceptos de tipos de datos abstractos y

ocultamiento de información en lenguajes de programación.

Page 24: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-24

Encapsulation of Operations, Methods, and Persistence (2)

Especificando Comportamiento del Objeto a través de las Operaciones de Clase:

La idea principal es definir el comportamiento de un tipo de objeto basado en las operaciones que pueden ser externamente aplicadas a los objetos de ese tipo.

En general, la implementación de una operación puede ser especificada en un lenguaje de propósito general que suministra flexibilidad y poder en la definición de operaciones.

Page 25: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-25

Encapsulation of Operations, Methods, and Persistence (3)

Especificando Comportamiento del Objeto a través de las Operaciones de Clase (cont.):

Para operaciones de BD, el requerimiento que todos los objetos están completamente encapsulados es también estricto.

Una forma de relajar este requerimiento es dividir la estructura del objeto en atributos divisibles y ocultos (variables de instancia)

Page 26: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-26

Encapsulation of Operations, Methods, and Persistence (4)

Adding operations to definitions of Employee and Department

Page 27: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-27

Encapsulation of Operations, Methods, and Persistence (5)

Especificando Persistencia del Objeto vía Nombrado y Alcanzabilidad

Mecanismo de Nombrado: Asigna un objeto a un nombre persistente único a través del cual este puede ser recuperado por programas.

Mecanismo de Alcanzabilidad: Hacer el objeto alcanzable desde el mismo objeto persistente.– Un objeto B se dice que es alcanzable desde un objeto A si

una secuencia de referenciais en el grafo del objeto lleva desde el objeto A hasta el objeto B.

Page 28: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-28

Encapsulation of Operations, Methods, and Persistence (6)

Especificando Persistencia del Objeto vía Nombrado y Alcanzabilidad (cont.):

En modelos de BD tradicionales tales como los modelos relacional o ERR, todos los objetos se asumen persistentes.

En el enfoque OO, una declaración de clase especifica solo el tipo y operaciones para una clase de objetos. El usuario tiene que por aparte que definir un objeto persistente de tipo set (DepartmentSet) o list (DepartmentList) cuyo valor es la colección de referencias a todos los objetos persistentes DEPARTMENT

Page 29: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-29

20.4 Type and Class Hierarchies and Inheritance (1)

Type (class) JerarquíaUn tipo en su forma más simple puede ser definido dando a

este un nombre de tipo y entonces listando los nombres de sus funciones visibles (public)

Cuando especificamos un tipo, se usa el siguiente formato, el cual no especifica argumentos de funciones, para simplificar la discusión: TYPE_NAME: function, function, . . . , function

Example:PERSON: Name, Address, Birthdate, Age, SSN

Page 30: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-30

Type and Class Hierarchies and Inheritance (2)

Subtipo: cuando el diseñador o usuario tiene que crear un nuevo tipo que es similar pero no idéntico a un tipo ya definido

Supertipo: Este hereda todas las funciones al subtipo

Page 31: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-31

Type and Class Hierarchies and Inheritance (3)

Example (1): PERSON: Name, Address, Birthdate, Age, SSN

EMPLOYEE: Name, Address, Birthdate, Age, SSN, Salary, HireDate, Seniority STUDENT: Name, Address, Birthdate, Age, SSN, Major, GPA

O:

EMPLOYEE subtype-of PERSON: Salary, HireDate, Seniority STUDENT subtype-of PERSON: Major, GPA

Page 32: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-32

Type and Class Hierarchies and Inheritance (4)

Example (2):

Considere un tipo que describe objetos en una geometría de planos, el cual puede ser definido como sigue:

GEOMETRY_OBJECT: Shape, Area, ReferencePoint

Page 33: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-33

Type and Class Hierarchies and Inheritance (5)

Example (2) (cont.):Ahora suponga que nosotros queremos definir un número de subtipos para el tipo GEOMETRY_OBJECT:

GEOMETRY_OBJECT: Shape, Area, ReferencePoint

RECTANGLE subtype-of GEOMETRY_OBJECT: Width, Height TRIANGLE subtype-of GEOMETRY_OBJECT: Side1, Side2, Angle CIRCLE subtype-of GEOMETRY_OBJECT: Radius

Page 34: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-34

Type and Class Hierarchies and Inheritance (6)

Example (2) (cont.):Una forma alternativa de declarar esos tres subtipos es especificar el valor del atributo Shape como una condición que tiene que ser satisfecha por los objetos de cada subtipo:

RECTANGLE subtype-of GEOMETRY_OBJECT (Shape=‘rectangle’): Width, Height

TRIANGLE subtype-of GEOMETRY_OBJECT (Shape=‘triangle’): Side1, Side2, Angle

CIRCLE subtype-of GEOMETRY_OBJECT (Shape=‘circle’): Radius

Page 35: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-35

Type and Class Hierarchies and Inheritance (7)

Extensión: En la mayoría de la BDOO, la colección de objetos en una extensión tiene el mismo tipo o clase.

Colección Persistente: Mantiene una colección de objetos que es almacenada permanentemente en la BD y pueden ser accesados y compartidos por múltiples programas

Colección Transitoria: Existe temporalmente durate la ejecución del programa pero no es mantenida cuando el programa termina

Page 36: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-36

20.5 Complex Objects (1)

Objetos complejos no estructurados: Son suministrados por el DBMS y permite el almacenamiento y recuperación de grandes objetos que necesitan las aplicaciones de BD.

Ejemplos típicos de tales objetos son bitmap

imágenes y documentos; también conocidos como binary large objects, or BLOBs .

Page 37: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-37

Complex Objects (2)

Objetos Complejos Estructurados: Difieren de un objeto complejo no estructurado en que la estructura del objeto es definida por la repetida aplicación del tipo de constructores suministrados por el OODBMS.

Entonces la estructura del objeto es definida y conocida por el OODBMS. El OODBMS también define métodos y operaciones para este.

Page 38: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-38

20.6 Other Objected-Oriented Concepts (1)

Polimorfismo (Operator Overloading):

Este concepto permite al mismo nombre de operador ó símbolo ser atado a dos o más diferentes implementaciones del operador, dependiendo del tipo de objetos al cual el operador es aplicado

Page 39: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-39

Other Objected-Oriented Concepts (2)

Herencia Múltiple y SelectivaHerencia múltiple en un tipo de jerarquía occurre cuando un cierto subtipo T es un subtipo de dos o más tipos y por lo tanto hereda las funciones (atributos y métodos) de ámbos supertipos.

Por ejemplo nosotros podemos crear un subtipo ENGINEERING_MANAGER que es un subtipo de ámbos MANAGER y ENGINEER. Esto dirige a la creación de un tipo lattice antes que un tipo jerarquía.

Page 40: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-40

Versiones y Configuraciones– Muchas aplicaciones de BD usan sistemas OO que

requieren la existencia de varias versiones del mismo objeto

Configuración:– Una configuración de un objeto complejo es una

colección consistente de una versión de cada módulo organizado en una forma tal, que las versiones del módulo en la configuración son compatibles y juntos forman una versión válida del objeto complejo.

Other Objected-Oriented Concepts (3)

Page 41: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-41

21.3 Object Query Language (OQL)

OQL is ODMG’s query languageOQL works closely with programming

languages such as C++Embedded OQL statements return objects

that are compatible with the type system of the host language

OQL’s syntax is similar to SQL with additional features for objects

Page 42: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-42

Simple OQL Queries

Basic syntax: select…from…where…SELECT d.nameFROM d in departmentsWHERE 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

Page 43: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-43

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

Page 44: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-44

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, e.g., departments; whose type is set<Department>

Page 45: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-45

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., d.chair (but not departments.chair);

Page 46: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-46

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

Page 47: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-47

An Example of OQL View

A view to include students in a department who have a minor:

define has_minor(dept_name) asselect sfrom s in studentswhere s.minor_in.dname=dept_name

has_minor can now be used in queries

Page 48: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-48

Single Elements from Collections

An OQL query returns a collectionOQL’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

Page 49: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-49

Collection Operators

OQL supports a number of aggregate operators that can be applied to query results

The aggregate operators include min, max, count, sum, and avg and operate over a collection

count returns an integer; others return the same type as the collection type

Page 50: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-50

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’);

Page 51: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-51

Membership and Quantification

OQL provides membership and quantification operators:– (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

Page 52: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-52

An Example of Membership

To retrieve the names of all students who completed CS101, the following attempt is incorrect:

select s.name.fname, s.name.lnamefrom s in studentswhere ‘CS101’ in(select c.name from c ins.completed_sections.section.of_course);

Page 53: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-53

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

Page 54: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-54

An Example of Ordered Operation

To retrieve the last name and salary of the faculty member who earns the highest salary:

first (select struct(faculty: f.name.lastname, salary: f.salary)from f in facultyorder by f.salary desc);

Page 55: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 21-55

Grouping Operator

OQL also supports a grouping operator called group by

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 studentsgroup by deptname: s.majors_in.dnamehaving count (partition) > 100

Page 56: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-56

20.7 Summary (1)

Object identity: Objects have unique identities that are independent of their attribute values.

Type constructors: Complex object structures can be constructed by recursively applying a set of basic constructors, such as tuple, set, list, and bag.

Encapsulation of operations: Both the object structure and the operations that can be applied to objects are included in the object class definitions.

Page 57: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-57

Summary (2)

Programming language compatibility: Both persistent and transient objects are handled uniformly. Objects are made persistent by being attached to a persistent collection.

Type hierarchies and inheritance: Object types can be specified by using a type hierarchy, which allows the inheritance of both attributes and methods of previously defined types.

Page 58: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-58

Summary (3)

Extents: All persistent objects of a particular type can be stored in an extent. Extents corresponding to a type hierarchy have set/subset constraints enforced on them.

Support for complex objects: Both structured and unstructured complex objects can be stored and manipulated.

Polymorphism and operator overloading: Operations and method names can be overloaded to apply to different object types with different implementations.

Versioning: Some OO systems provide support for maintaining several versions of the same object.

Page 59: Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc

Copyright © 2004 Ramez Elmasri and Shamkant NavatheElmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-59

Current Status

OODB market not growing much per se. Currently around $250M as opposed to the relational DB revenue upwards of $50B.

O-O ideas are being used in a large number of applications, without explicitly using the OODB platform to store data.

Growth: O-O tools for modeling and analysis, O-O Programming Languages like Java and C++

Compromise Solution Proposed: Object Relational DB Management (Informix Universal Server, Oracle 10i, IBM’s UDB, DB2/II …)