La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

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

Presentaciones similares


Presentación del tema: "Chapter 20 - 21 Bases de Datos Orientadas a Objetos Copyright © 2004 Pearson Education, Inc."— Transcripción de la presentación:

1

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

3 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

4 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.

5 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

6 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

7 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

8 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.

9 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.

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

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

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

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

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

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

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

17 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Chapter 20-17 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, ‘1988-05-22’) 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’}.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

47 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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) as select s from s in students where s.minor_in.dname=dept_name has_minor can now be used in queries

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

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

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

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

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

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

54 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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 faculty order by f.salary desc);

55 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/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 students group by deptname: s.majors_in.dname having count (partition) > 100

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

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

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

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


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

Presentaciones similares


Anuncios Google