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

Slides:



Advertisements
Presentaciones similares
Programación orientada a objetos en Visual Basic .NET
Advertisements

Diseño de Bases de Datos
Unidad 3 Lenguajes .Net y POO
Curso de java básico (scjp)
Curso de Java Capitulo 7: Conceptos sobre poo Profesor:
BASE DE DATOS OBJETO RELACIONAL
HERRAMIENTA PARA LA RECUPERACION DE INFORMACION: KARPANTA, un motor de búsqueda experimental Oscar Andrés Seoneray Cod
Control en cascada.
Arquitectura CLARO-TECNOTREE
Introducción 1 Puntos Clave –La orientación a objetos representa un cambio radical en los métodos tradicionales de creación de software –Los métodos tradicionales.
Teórico: Introducción
Lenguaje de consulta de Hibernate
Julio Pacheco SQL SERVER 2005 XML APRENDIENDO CON EJEMPLOS.
UNIVERSIDAD LATINA (UNILA) ENCAPSULACION Y HERENCIA
Aplicación del paradigma orientado a objetos
INTRODUCCIÓN A UML Oscar Miguel Alonso Moreno.
Oracle, orientado a objetos
Encapsulamiento y Abstracción
Programación Orientada a Objetos en Java
4.3. Privilegios de usuarios
BASES DE DATOS ORIENTADAS A OBJETO
saquen la tarea en la página 57, ejercicio 1 ejemplos 4 y 5
BASE DE DATOS DISTRIBUIDAS
Lic. Rosemary Torrico Bascopé
Abstracción de los datos y Orientación a Objeto Clase 13.
PL/SQL Francisco Moreno Universidad Nacional.
Universidad Autónoma del Estado de Hidalgo Instituto de Ciencias Básicas e Ingeniería Área Académica de Computación y Electrónica Licenciatura en Ciencias.
Tema 6: Clases Antonio J. Sierra.
Introducción a la programación Orientada a objetos
1 Herencia en Java Agustín J. González Diseño y Programación Orientados a Objetos.
BASES DE DATOS ORIENTADAS A OBJETOS
SQL.
INTRODUCCIÓN A LA PROGRAMACIÓN ORIENTADA A OBJETOS Objetos.
Subconsultas Avanzadas
Ingeniería de Software
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
Gestión de Objetos con Vistas de Diccionario de Datos
Bases de Datos Orientadas a Objetos (BDOO)
Programación Orientada a Objetos en Java
INTRODUCCIÓN A LA PROGRAMACIÓN ORIENTADA A OBJETOS Encapsulamiento.
4.1 Continuidad en un punto 4.2 Tipos de discontinuidades 4.3 Continuidad en intervalos.
Object Definition Language
CS-432: Ingeniería Moderna de Software Semana 3
CPU 8088 vs. Pentium TEEL 4011 Prof. Jaime José Laracuente-Díaz.
Diseñando la arquitectura de aplicaciones empresariales. Acceso al SQL Server.- Autenticación de usuario:
MODELO ORIENTADO A OBJETOS
"Y todo lo que hagáis, hacedlo de corazón, como para el Señor y no para los hombres" (Colosenses 3:23) Prof. Leonid Tineo Departamento de Computación Universidad.
Programación en Visual Basic Lección #8: SQL Por Antonio F. Huertas.
SCJP SUN CERTIFIED PROGRAMMER FOR JAVA 6
Write the letter of the correct definition or sentence next to the word below. 1.________ Algebraic Expression 2.________ Equation 3.________ Exponent.
(c) P. Gomez-Gil, INAOEP DISEÑO DE SOFTWARE 2ª. parte NOTAS DEL CURSO Ingeniería de Software I DRA. MARIA DEL PILAR GÓMEZ GIL INAOEP Versión:
DHCP, DNS, WINS. Repaso..
Desarrollo de aplicaciones empresariales con Web Services
1 Herencia en Java Agustín J. González Diseño y Programación Orientados a Objetos.
Servlets Servlets son módulos que extienden a servidores orientados a request/response, como por ejemplo Servidores Web “java-enabled”. Un servlet puede.
Herencia. Introducción La idea básica es poder crear clases basadas en clases ya existentes. Cuando heredamos de una clase existente, estamos re-usando.
Facultad de Ingeniería
Programación Orientada a Objeto
PROGRAMACIÓN ORIENTADA A OBJETOS Unidad 1 GENERICIDAD
¿Qué haces en la escuela? Question words, objects, yo-go’s.
MSSQL SERVER CURSO BÁSICO 1. CONCEPTOS BASICOS DE SQL. DESCRIPCIÓN DEL CURSO. Sesión 3: Índices Uso, Creación, Tipos, Eliminación LENGUAJE DE CONSULTAS.
Abstracción El concepto de abstracción es esencial en ciencias de la computación. Un programa es en sí mismo una abstracción, un modelo de la resolución.
VARIABLES BINARIAS Y ENTERAS
La Programación Orientado a Objetos
Double Object Pronouns What happens when we have both direct and indirect object pronouns in the same sentence? What goes where? Information for this lesson.
Introducción AOO. Contenido - Introducción - Repaso de Orientación a Objetos - UML - Casos de Uso.
Después de completar esta lección, debe ser capaz de:  Crear registro definidos por el usuario.  Crear un registro con el atributo %ROWTYPE.  Crear.
Factorías e Iterables Introducción del concepto de patrón de diseño Construcción de tipos para recorridos con for extendido Fundamentos de Programación.
INTRODUCCIÓN A LA PROGRAMACIÓN ORIENTADA A OBJETOS Encapsulamiento.
Transcripción de la presentación:

Chapter Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-3 Contenido 20.1 Conceptos fundamentales 20.2 O-O Identidad, Estructura y Tipo de los Constructores de Objetos 20.3 Encapsulación de Operaciones, Métodos y Persistencia 20.4 Tipo y Jerarquía de Clases y Herencia 20.5 Objectos Complejos 20.6 Otros Conceptos O-O 21 Object Query Language (OQL) 20.7 Resumen y Estado Actual

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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’s Razones 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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 …..

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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)

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Ejemplo 1, un posible estado de una BD relacional correspondiente al esquema COMPANY

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Ejemplo 1 (cont.):

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Example 1 (cont.)

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Identidad, Estructura, y Tipos de Constructores de Objetos Example 1 (cont.) Usamos i 1, i 2, i 3,... para identificadores de objetos únicos generados por el sistema. Considere los siguientes objetos: o 1 = (i 1, atom, ‘Houston’) o 2 = (i 2, atom, ‘Bellaire’) o 3 = (i 3, atom, ‘Sugarland’) o 4 = (i 4, atom, 5) o 5 = (i 5, atom, ‘Research’) o 6 = (i 6, atom, ‘ ’) o 7 = (i 7, set, {i 1, i 2, i 3 }) Objetos o 1 al o 6 representan valores atómicos. o 7 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’}.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Identidad, Estructura, y Tipos de Constructores de Objetos Example 1(cont.) o 8 = (i 8, tuple, ) o 9 = (i 9, tuple, ) o 10 = (i 10, set, {i 12, i 13, i 14 }) o 11 = (i 11, set {i 15, i 16, i 17 }) o 12 = (i 12, tuple, )... Object 8 es un objeto tipo tuple que representa el departmento, y tiene los atributos DNAME, DNUMBER, MGR, LOCATIONS, EMPLOYEES Y PROJECTS.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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. o 1 = (i 1, tuple, ) o 2 = (i 2, tuple, ) o 3 = (i 3, tuple, ) o 4 = (i 4, atom, 10) o 5 = (i 5, atom, 10) o 6 = (i 6, atom, 20) Los objetos o 1 y o 2 tienen estados iguales, porque sus estados a nivel atómico son los mismos pero sus valores son alcanzados a traves de distintos objetos o 4 and o 5. Sin embargo los estados de los objetos o 1 and o 3 son idénticos, aunque los objetos por ellos mismos no lo son porque ellos tienen diferentes OIDs. Similarmente, aunque los estados de o 4 and o 5 son idénticos, los objetos actuales o 4 and o 5 son iguales pero no idénticos, porque ellos tienen distintos OIDs.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Identidad, Estructura, y Tipos de Constructores de Objetos Figure 20.1 Representation of a DEPARTMENT complex object as a graph

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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 basados ODL 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Tipos de Constructores de Objetos (ODL) Specifying the object types Employee, Date, and Department using type constructors

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Encapsulation of Operations, Methods, and Persistence (1) Encapsulación Es 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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)

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Encapsulation of Operations, Methods, and Persistence (4) Adding operations to definitions of Employee and Department

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Type and Class Hierarchies and Inheritance (1) Type (class) Jerarquía Un 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Other Objected-Oriented Concepts (2) Herencia Múltiple y Selectiva Herencia 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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)

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter Object Query Language (OQL) OQL is ODMG’s query language OQL 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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 );

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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’);

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.lname from s in students where ‘CS101’ in (select c.name from c in s.completed_sections.section.of_course);

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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 faculty order by f.salary desc);

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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 students group by deptname: s.majors_in.dname having count (partition) > 100

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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.

Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 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 …)