Escolar Documentos
Profissional Documentos
Cultura Documentos
COPPE/UFRJ
Contedo
Introduo ! Orientao a Objetos e Bancos de Dados ! O Modelo Orientado a Objetos
!
"O
Padro ODMG
Consideraes Finais
2
Referncias Bibliogrficas
!
"The Object Database Standard: ODMG 3.0 R. G. Cattell e D. K. Barry (editores) Morgan Kaufmann Publishers, 2000 "Object Data Management" R. G. Cattell Addison-Wesley, 1994 UML Distilled: Applying the Standard Object Modeling Language M. Fowler e K. Scott Addison Wesley, 2000, 2a edio Database System Concepts A. Silberschatz, H. Korth, e S. Sudarshan Mc-Graw-Hill, 2002, 4a edio
3
Referncias Bibliogrficas
!
Object Databases: An ODMG Approach R. Cooper International Thomson Computer Press (edio eletrnica), 1997 Object-Relational DBMSs: The Next Great Wave M. Stonebraker, D. Moore Morgan Kaufmann, 1996 The BUCKY Object-Relational Benchmark M.Carey, D. DeWitt, J.Naughton et al. Relatrio Tecnico- U.Wisconsin (http://www.cs.wisc.edu/~naughton/bucky.html) From UML to ODMG: Modeling and Implementing Object Oriented Database Applications Based on Standards, R.C. Mauro, M.L.Q. Mattoso Tutorial XIV SBBD (http://www.cos.ufrj.br/~marta) Processamento de Consultas Orientadas a Objetos Mattoso, M.L.Q. Ruberg, G. Victor, A. Baio, F. Relatrio Tecnico- COPPE ES-547/01 (http://www.cos.ufrj.br)
Motivao
Caractersticas da Orientao a Objetos Modelagem fcil e intuitiva do mundo real Funcionalidades de Banco de Dados Compartilhamento seguro de informaes persistentes Evoluo dos modelos de gerncia e manipulao de dados
UML
02 98 Modelo UML Tamino (XML) 94 SGBDs Universais Modelos OO/OR 90 Ontos, O2, Postgres Adaplex Exodus SDM
74 70 66 62 58
Padro UML
! !
Restries complexas Estruturas de dados complexas Identidade de objetos e referncias diretas Cdigo de aplicao interno ao banco de dados
Objetos
" Encapsulamento
Classes
" Atributos " Mtodos
Relacionamentos
" Herana " Associao " Agregao
Identidade de Objetos
10
Exemplo: Bucky
1..1 +worksIn 0..1
1..1 +major
Instructor totalCreditsSemester()
+hasTaken 0..* +teacher 1..1 +advisor 1..1
Enrolled grade
+students 0..* 0..* +coursesOffered 1..1 +section 1..1 +Course 0..* +Sections
TA semesterSalary Salary()
+teaches 0..*
11
Objetos
!
de variveis que armazenam o estado do objeto " conjunto de mensagens s quais o objeto responde " conjunto de mtodos contendo cdigo de programa que implementa uma mensagem
!
Classes
! !
da classe
13
Representao de Classes
Classe = Atributos + Mtodos
Employee
Nome da classe
Atributos
dateHired status
Salary()
Mtodos
Atributo-relacion.
worksIn
14
Relacionamentos
!
/ Agregao
15
Relacionamentos
!
/ Agregao
16
Herana
Conceito ! Representao da Herana ! Classes Abstratas ! Polimorfismo ! Propriedade da Substituio ! Colees Polimrficas
!
17
Conceito de Herana
! !
Classes mais especializadas (subclasses) herdam as propriedades (atributos e mtodos) das suas super-classes Mtodos de uma classe podem ser chamados para objetos de qualquer uma das suas subclasses
18
Representao de Herana
Person id name street state birthdate kidNames picture place Employee DateHired status Salary() TA semesterSalary Staff annualSalary Salary() Salary() Instructor totalCreditsSemester()
19
Herana Mltipla
Instructor totalC reditsSemester() printGrades() S tudent studentId
TA semesterSalary S alary()
20
10
Classe Abstrata
Employee DateHired status Salary()
Instructor totalCreditsSemester()
TA semesterSalary Salary()
21
Polimorfismo
Employee DateHired status Salary()
Objetos Objetosde dediferentes diferentes classes classesrespondem respondemmesma mesma mensagem de diferentes mensagem de diferentesmaneiras maneiras
Instructor totalCreditsSemester()
TA semesterSalary Salary()
22
11
Propriedade da Substituio
Employee e; TA ta; Prof pr; Staff st; ... // instanciao das variveis e = ta; e.Salary(); e = pr; e.Salary(); e = st; e. Salary();
TA Prof Staff
23
Colees Polimrficas
Employees
Prof
Staff
Prof
Staff
Staff
Prof
TA
Prof
Prof
for( for( int int i i= = 0; 0; i i< < Employees.length; Employees.length; i++ i++ ){ ){ e = Employees[i]; e = Employees[i]; System.out.println( System.out.println( e.name e.name ); ); System.out.println( e.Salary() System.out.println( e.Salary() ); ); } }
24
12
Relacionamentos
!
/ Agregao
25
Associao Simples
Department dno name building budget SumSalary() performPayment()
0..* +students
1..1 +major
26
13
Associao Unidirecional
Department dno name building budget SumSalary() performPayment()
chair
1..1
27
Relacionamentos
!
/ Agregao
28
14
Agregao
!
+course 1..1
29
Objetos compostos
!
Captulos podem ser agrupados para formar um livro Pargrafos formam uma seo, sees formam um captulo ...
15
Identidade de Objetos
Cada objeto possui uma identidade independente do seu estado ! O estado pode ser modificado sem mudar a identidade ! Idnticos e Iguais so dois conceitos diferentes (profundidade) ! Conceito de chave deve ser preservado
!
31
O Padro ODMG
16
Grupo formado pelos principais fabricantes de banco de dados OO alm de um grande nmero de empresas interessadas num padro para SGBDOO. ODMG 3.0
"
"The Object Database Standard: ODMG 3.0, Cattell et al. (ed), Morgan Kaufmann Publishers, 2000 Base para a especificao do Java Data Objects (JDO) OMG, SQL:99 XML: linguagem de especificao de objetos ODMG baseada em XML (OIFML)
! !
Java Binding
" " "
http://www.odmg.org
33
Banco de Dados OO
! ! ! ! ! ! ! !
GOA (COPPE/UFRJ) Cach db4o Javera Jasmine - CA JDBCStore Jodad Jevan - W3Apps
! ! ! ! ! ! ! !
17
Importncia do Padro
!
SQL
" Independncia
ODMG
" Independncia
+
" Harmonia
!
" Aplicaes
ODMG - Arquitetura
Tela1
80 70 60 50 40 30 20 10 0 A B C
Tela1
80 70 60 50 40 30 20 A B C
Tela
10 0
begin Class X ... A : integer ... B : integer ... C : integer end Memria
Class X A : integer B : integer C : integer
Disco
Sistema Tradicional
SGBDOO
36
18
Relacionamentos
herana mltipla (ISA, EXTENDS)
38
19
Mapeamento de interfaces
UML
ODMG
Mapeamento de classes
UML
Course cno name credits
ODMG
};
40
20
41
21
Atributos
! ! !
class class Course Course name: name: string, string, : cno : integer integer cno dept dept : : Department Department sections: sections: list[CourseSection], list[CourseSection], ... ... ? ?
43
Atributos simples
! !
string...
Dependendo Dependendoda daimplementao, implementao,os ostipos tiposbsicos bsicospodem podemser sertratados tratados sintaticamente e semanticamente como objetos. Esta abordagem sintaticamente e semanticamente como objetos. Esta abordagem porm pormno no vantajosa vantajosaquanto quantoa aeficincia. eficincia.
44
22
Atributos complexos
!
Referncias (relacionamento)
" No
podem ser corrompidas. A referncia invalidada automaticamente quando o objeto referenciado apagado. " Independente dos valores do objeto referenciado. (Identidade)
45
Atributos complexos
!
Colees
" listas " conjuntos " vetores
Primeira forma normal violada ! Possibilidade de estabelecer uma ordem entre os elementos
!
46
23
Atributos complexos
!
virtuais
POSTGRES, O2
" Atualizao
!
de atributos derivados
47
Relacionamentos
Nome ! Grau (binrio, n-rio) ! Cardinalidade
!
Direo
24
Relacionamentos
Associao (UML) # Relacionamento (ODMG)
! ! !
Binria Unidirecional
" atributo
de referncia
Binria bi-direcional
" relacionamento
classe relacionamento
49
Relacionamentos
Associao Unidirecional
Department dno name building budget SumSalary() performPayment() Professor AYSalary monthSummer 0..1 Salary()
class Professor (extent professors){ attribute short AYSalary; attribute short monthSummer; double Salary() }; 50
+chair 1..1
class Department (extent departments, key dno) { attribute short dno; attribute string name; attribute Professor chair; };
25
Relacionamentos
Associao Bidirecional
Department dno name building budget SumSalary() performPayment()
0.. * +students
1..1 +major
51
Relacionamentos
Associao Bidirecional # Atributo Inverso
class Department (extent departments, key dno) { attribute short dno; attribute string name; attribute string building; attribute string budget; relationship set <Student>students inverse Student::major; double sumSalary(); void performPayment(); }; class Student (extent students, key studentId) { attribute short studentId; relationship <Department> major inverse Department ::students; void printGrades(); };
52
26
Relacionamentos
Associao Binria N x M
CourseSection Student studentId printGrades() +hasTaken 0..* +students 0..* semester textbook building room numberOfStudents() printClassDiary()
53
Relacionamentos
Associao Binria N x M # Atributo Inverso
class Student (extent students, key studentId) { attribute short studentId; relationship set <CourseSection > hasTaken inverse CourseSection::students; ...}; class CourseSection (extent coursesections) { attribute short semester; attribute string textbook; attribute string building; attribute short roomNo; attribute short noStudents; relationship set <Student> students inverse Student::hasTaken; ...};
54
27
Relacionamentos
Associao Binria N x M
CourseSection Student +hasTaken Enrolled +section 0..* 1..1 +student grade +students printGrades() 1..1 0..* studentId semester textbook building room numberOfStudents() printClassDiary()
55
Relacionamentos
Associao Binria com Atributo ...
class Student (extent students, key studentId) { attribute short studentId; relationship set <Enrolled> hasTaken inverse Enrolled::students; void printGrades(); }; class CourseSection (extent coursesections) { attribute short semester; attribute string textbook; attribute string building; attribute short roomNo; attribute short noStudents; relationship set <Enrolled> students inverse Enrolled::section; };
56
28
Relacionamentos
Associao Binria com Atributo (cont.)
class Enrolled (extent enrolleds) {attribute real grade; relationship <Student> student inverse Student::hasTaken; relationship <CourseSection> section inverse CourseSection ::students;
57
Relacionamentos
Associao Binria com Atributo (ex. O2 ODMG)
class CourseSection (extent coursesections) { attribute short semester; attribute string textbook; attribute string building; attribute short roomNo; attribute short noStudents; relationship set < Student > students inverse Student::section; }; class Student (extent students, key studentId) { attribute short studentId; relationship set struct ( <CourseSection > hasTaken, real grade ) section inverse CourseSection::students; void printGrades(); };
58
29
Relacionamentos
!
Relacionamento no binrio
" H
necessidade de criao de uma classe especfica para expressar o relacionamento " A notao . reduz os inconvenientes da nova classe
59
Relacionamentos
Associao Ternria
Student * students Course course 1..1 CourseSection semester textbook teacher Instructor 1..1
class Course { ... } ; class Student { ... } ; class Instructor { ... } class CourseSection (extent courseSections key(course,students,teacher)) { relationship Course course; relationship set<Student>students; relationship Instructor teacher; attribute integer semester; attribute string textbook; ... };
60
30
Herana Simples
Person id name street state birthdate kidNames picture place
class Person ( extent people, key id ) { attribute int id; attribute string name; ... } class Student extends Person ( extent students, key studentId ) { attribute int studentId; }
61
31
Herana Mltipla
class TA extends Student, Instructor { attribute date DateHired; attribute string status; attribute double semesterSalary; relationship ... double Salary(); }
TA semesterSalary S ala ry()
63
S tudent studentId
printGrades()
64
32
65
Predicado Predicado
! ! !
33
resultado representa uma das variveis (ou combinao) presentes em operando e identifica a origem da lista de objetos/valores que ser fornecida como resultado da consulta operando da consulta consiste de expresses do tipo coleo v ,onde v representa os objetos em coleo predicado o conjunto de clusulas que representam as condies que devem ser satisfeitas pelas variveis de lista de variveis
67
Expresses de Caminho
courses courses c c c.dept.chair.name c.dept.chair.name c.dept.chair.advisees c.dept.chair.advisees c.dept.students c.dept.students
Course cno name credits +dept 1..1 +coursesOffered 0..* SumSalary() performPayment() 1..1 +chair +students 0..1 Professor AYSalary +advisees monthSummer 0..* 0..* Salary()
68
Student studentNo
printGrades()
34
Expresses de Caminho
OQL SQL
select select c.name c.name select from select c.name c.name from Course Course c, c, Department Department d, d, from Professor from courses courses c c Professor p p where ; where where c.dept.chair.state c.dept.chair.state = = AM AM ; where c.dept c.dept = = d.dno d.dno and d.chair and d.chair = = p.id p.id and ; and p.state p.state = = AM AM ;
Department dno name building budget
+dept 1..1
+coursesOffered 0..*
Student studentNo
SumSalary() performPayment() 1..1 +chair +students 0..1 Professor AYSalary +advisees monthSummer 0..* 0..* Salary()
printGrades()
69
Expresses de Caminho
OQL
select select c c from , from courses courses c c , c.dept.students c.dept.students s s where where s.city s.city = = Manaus; Manaus;
SQL
select select c.* c.* from , from Course Course c c , Department , Department d d , Student Student s s where c.dept = d.dno where c.dept = d.dno and and d.dno d.dno = = s.majors s.majors and and s.city s.city = = Manaus; Manaus;
Department dno name building budget
+dept 1..1
+coursesOffered 0..*
Student studentNo
SumSalary() performPayment() 1..1 +chair +students 0..1 Professor AYSalary +advisees monthSummer 0..* 0..* Salary()
printGrades()
70
35
Expresses de Caminho
OQL SQL
select d.*, d.*, s.name s.name select select struct struct (dept:d, (dept:d, std:s.name) std:s.name) select from Department d, from Department d, from departments d , from departments d, Professor p, Student Professor p, Student s s d.chair.advisees s d.chair.advisees s where d.chair = p.id where d.chair.name = Altigran; where d.chair = p.id where d.chair.name = Altigran; and and s.advisor s.advisor = = p.id p.id and and p.name p.name = = Altigran; Altigran;
Department dno name building budget
+dept 1..1
+coursesOffered 0..*
Student studentNo
SumSalary() performPayment() 1..1 +chair +students 0..1 Professor AYSalary +advisees monthSummer 0..* 0..* Salary()
printGrades()
71
OQL
+chair 1..1
0..* +students
1..1 +major
+hasTaken 0..*
Instructor totalCreditsSemester()
+teaches 0..* +advisee 0..*
Enrolled grade
1..1 +section +dept 1..1 +students 0..* 0..* +sections 1..1 +course
TA semesterSalary Salary()
+teacher 1..1
72
36
Herana
OQL
select select e.name, e.name, e.street, e.street, e.zip e.zip from employees SQL from employees e e where select e.name, e.street, e.zip where e.DateHired e.DateHired > > 2000; 2000; select e.name, e.street, e.zip from from Staff Staff e, e, Employee where e.DateHired > where e.DateHired > 2000; 2000; DateHired UNION ALL status UNION ALL select select e.name, e.name, e.street, e.street, e.zip e.zip Salary() from Professors from Professors e e where where e.DateHired e.DateHired > > 2000; 2000; UNION ALL UNION ALL Staff Instructor select select e.name, e.name, e.street, e.street, e.zip e.zip annualSalary from from TA TA e e totalCreditsSemester() Salary() where where e.DateHired e.DateHired > > 2000; 2000;
Professor AYSalary monthSummer Salary() TA semesterSalary Salary()
73
Herana e associao
OQL
select select e.name, e.name, e.street, e.street, e.zip e.zip from from employees employees ee where e.DateHired > 2000 where e.DateHired > 2000 and and e.worksin.budget e.worksin.budget >> 10k; 10k;
SQL
select select e.name, e.name, e.street, e.street, e.zip e.zip from from Staff Staff e, e, Department Department dd where where e.DateHired e.DateHired >> 2000 2000 and and d. d. budget budget >> 10k 10k and and e.worksin e.worksin == d.deptNo; d.deptNo; UNION UNION ALL ALL select select e.name, e.name, e.street, e.street, e.zip e.zip from from Staff Staff e, e, Department Department dd where e.DateHired > 2000 where e.DateHired > 2000 and and d. d. budget budget >> 10k 10k and and e.worksin e.worksin == d.deptNo; d.deptNo; UNION UNION ALL ALL select select e.name, e.name, e.street, e.street, e.zip e.zip from from Staff Staff e, e, Department Department dd where e.DateHired > 2000 where e.DateHired > 2000 and and d. d. budget budget >> 10k 10k and and e.worksin e.worksin == d.deptNo; d.deptNo;
Instructor
totalCreditsSemester()
TA
semesterSalary
Salary()
74
37
Polimorfismo
OQL
select x.name, x.salary from employees x where x.salary >= 96000;
SQL
select x.name, x.salary from Staff x where x.annualSalary >= 96000 union all select x.name, x.salary from Professor x where (x.salary*(9+x.monthSummer)/9.0) >= 96000 union all select x.name, x.salary from TA x where (apptFraction*(2*x.salary)) >= 96000
75
Pertinncia de conjuntos
OQL
select x.name, x.salary from staffs x where Maria IN x.kidNames;
SQL
select from where and x.name, x.salary Staff x, Kids k x.id = k.id k.kidName = Maria
76
38
Estratgias de Processamento
!
Direo
!
Operador
!
Estratgias de Processamento
select c from courses c, c.dept.students s where s.city = Manaus;
courses
departments
students
78
39
Estratgias de Processamento
select c from courses c, c.dept.students s where s.city = Manaus;
courses
departments
students
79
Estratgias de Processamento
select c.name from courses c where c.dept.chair.state = AM;
courses
departments
professors
80
40
Estratgias de Processamento
select c.name from courses c where c.dept.chair.state = AM;
courses
departments
professors
OQL / ODL
! ! ! !
OQL estendida com primitivas para minerao de dados em bases de objetos Processamento Paralelo de Consultas Interface com a linguagem Java Armazenamento de documentos XML www.cos.ufrj.br/~goa
82
41
Objeto
" Sistema
de tipos mais rico - Tipos de dados complexos " Manipulao de objetos pelo usurio " Extenso da linguagem SQL
!
SQL:1999, SQL:200n...
84
42
Resposta dos Bancos de Dados Relacionais Orientao a Objetos Migrao transparente Incorpora novas funcionalidades e capacidade de modelagem para tratar dados complexos (objetos) sobre estruturas fsicas relacionais (tabelas)
" Representaes " Gap
semntico
85
Documentos XML
! ! ! !
Herana
"
Expresses de caminho
86
Funes e Procedimentos
43
Relaes Aninhadas
!
" Fisicamente,
87
Relaes Aninhadas
Department name cityName SumSalary() performPayment()
0..* +students 1..1 +major
cityName
San Diego New York
students
{David Dewitt, Eddie Smith} {Susan Smith} {Jonh Walsh, George Gold}
...
88
44
Relaes Aninhadas
Department name cityName SumSalary() performPayment()
0..* +students 1..1 +major
kidNames
{David, Mary, John} {Carol, Steve} {Emily, Mary}
...
89
Tipos Complexos
!
Colees
" Conjuntos
!
" Representao
90
45
Tipos Complexos
!
Objetos Longos
" Fotografias,
imagens mdicas de alta resoluo, vdeos " Representao direta de objetos da aplicao, armazenados na base de dados
!
" tipos
! !
91
Tipos Complexos
!
Tipos Estruturados
" Atributos
46
Tipos Complexos
!
Tipos Estruturados
" Mtodos
!
create ( create type type Professor Professor as as ( name (20), name varchar varchar (20), AYsalary AYsalary integer integer ) ) method giveraise(percent ) method giveraise(percent integer integer ) create ) create method method giveraise(percent giveraise(percent integer integer ) for for Professor Professor begin begin set .AYsalary .AYsalary set self self .AYsalary = = self self .AYsalary + + ( self .AYsalary ( self .AYsalary * * percent)/100; percent)/100; end end
93
Tipos Complexos
!
Tipos Estruturados
" Valores
!
create (20), (20)) create function function Department( Department( n n varchar varchar (20), b b varchar varchar (20)) returns Department returns Department begin begin set set name name = = n; n; set cityName ; set cityName = =b b ; end end insert insert into into Students Students values values ( Sarah , array [ Dave , Linda ], 17-oct-1970 , (Sarah, array [ Dave , Linda ], 17-oct-1970 , Department( computer , San )) Department( computer Science Science , San Diego Diego ))
94
47
Herana - de Tipos
! ! !
Polimorfismo
Professor AYsalary
Herana - de Tabelas
! ! !
Especializao/generalizao do modelo E-R Tipos das tabelas filhas devem ser sub-tipos da tabela pai Todas as tuplas das tabelas filhas esto implicitamente presentes na tabela pai
!
Consultas tabela People (do tipo Person) retornam tuplas das tabelas People, Students e Professors only People permite consultas apenas tabela People
create create table table People People of of Person Person create create table table Students Students of of Student Student under under People People create create table table Professors Professors of of Professors Professors under under Person Person
96
48
Herana - de Tabelas
!
Atributos em comum apenas na tabela pai Atributos em comum replicados nas tabelas filhas
chave primria atributos em comum
Superclasse Subclasses
atributos especficos chave primria
97
Tipo Referncia
! !
um ponteiro lgico para um objeto de um tipo Modelam relacionamentos de associao entre objetos evitando o uso de chaves estrangeiras
create create type type Department( Department( name varchar (20), name varchar (20), cityName varchar(20, cityName varchar(20, chair (Professor) chair ref ref (Professor) scope scope Professors) Professors) create create table table Departments Departments of of Department Department insert Geology , San , insert into into Departments Departments values values ( ( Geology , San Diego Diego , null) null) update update Departments Departments set (p) set chair chair = =( ( select select ref ref (p) from from Professors Professors as as p p where name = John ) where name = John) where Geology where name name = = Geology
98
49
Consultas
!
atributos do tipo referncia " Provm um fcil e intuitivo mecanismo de navegao entre os objetos " simplificam consultas
!
" Algoritmos
!
99
Linguagem de programao
" Bindings
para Java, C, C++ " PL/SQL (Oracle), TransactSQL (MS SQL Server)
100
50
101
O SBBDRO Oracle
51
ORACLE 9i
! ! !
SGBD Relacional Objeto compatvel com padro SQL:1999 API para C++ seguindo especificao padro da ODMG Recursos
" Tipo
Objeto " Tipo REF " Viso de Objetos " Colees " ... (herana, mtodos, ...) " Armazenamento dados XML (CLOB)
103
Tipo Objeto
!
CREATE TYPE T_PESSOA AS OBJECT ( NOME VARCHAR2(30), TELEFONE VARCHAR2(20) ); CREATE TABLE TAB_PESSOA OF T_PESSOA; INSERT INTO TAB_PESSOA VALUES ( "John Smith", "1-800-555-1212" ); SELECT VALUE(P) FROM TAB_PESSOA P WHERE P.NOME = "John Smith";
104
52
Tabelas de Objetos
!
" tabela
!
105
Tipo REF
! !
! !
um ponteiro lgico para um objeto Tipos REF e colees de REFs modelam associaes entre os objetos evitando o uso de chaves estrangeiras Provm um fcil e intuitivo mecanismo de navegao entre os objetos, notao ponto . Segundo a prpria Oracle, as operaes de juno so evitadas sempre que possvel
106
53
Tipo REF
! !
Implementao Oracle para o tipo Referncia Referncias podem se tornar invlidas (is dangling) por causa da remoo do objeto
CREATE TYPE T_PESSOA AS OBJECT ( NOME VARCHAR2(30), TELEFONE VARCHAR2(20), DATA_NASCIMENTO DATE, PAI REF T_PESSOA SCOPE IS TAB_PESSOA, MEMBER FUNCTION GET_NOME RETURN VARCHAR, ORDER FUNCTION MATCH( P T_PESSOA ) RETURN INTEGER); DECLARE REF_PESSOA REF TO T_PESSOA; SELECT REF(P) INTO REF_PESSOA FROM TAB_PESSOA P WHERE P.NOME = MARTA MATTOSO;
107
Desreferenciando REFs
Acessar o objeto referenciado por um REF significa desreferenciar um REF ! O Oracle prov o operador DEREF para desreferenciar um REF ! Desreferenciar um Dangling REF retorna um ponteiro NULL
!
108
54
Obtendo REFs
Pode-se obter o REF de um objeto utilizando-se o operador REF em uma consulta ! A consulta s pode retornar um nico objeto
!
DECLARE REF_PESSOA REF TO T_PESSOA; SELECT REF(P) INTO REF_PESSOA FROM TAB_PESSOA P WHERE P.NOME = FERNANDA;
109
Viso de Objetos
CREATE TABLE EMP ( ID NUMBER (5), NOME VARCHAR2 (20), SALARIO NUMBER (9, 2), ); CREATE TYPE T_EMP ( ID NUMBER (5), NOME VARCHAR2 (20), SALARIO NUMBER (9, 2), ); CREATE VIEW V_EMP OF T_EMP WITH OBJECT IDENTIFIER (ID) AS SELECT E.ID, E.NOME, E.SALARIO FROM EMP E WHERE SALARIO > 2000;
110
55
Colees
!
Estes tipos de coleo podem ser utilizados em qualquer lugar onde os outros tipos podem ser utilizados
111
VARRAYs
CREATE TYPE T_TELEFONES AS VARRAY(3) OF VARCHAR2(20); CREATE TYPE T_PESSOA AS OBJECT ( NOME VARCHAR2(30), TELEFONES T_TELEFONES, DATA_NASCIMENTO DATE, PAI REF T_PESSOA SCOPE IS TAB_PESSOA, MEMBER FUNCTION GET_NOME RETURN VARCHAR, ORDER FUNCTION MATCH( P T_PESSOA ) RETURN INTEGER ... );
112
56
Nested Tables
CREATE TYPE T_TELEFONES AS TABLE OF T_TELEFONE; CREATE TYPE T_PESSOA AS OBJECT ( NOME VARCHAR2(30), TELEFONES T_TELEFONES, DATA_NASCIMENTO DATE, ... ) NESTED TABLE TELEFONES STORE AS TAB_TELEFONES;
113
Consultas em Colees
SELECT P.NOME, P.TELEFONES FROM TAB_PESSOA P; NOME TELEFONES -------- -------MARY T_TELEFONES(1234-5678, 2222-3333)
SELECT P.NOME, TEL.* FROM TAB_PESSOA P, TABLE(P.TELEFONES) TEL; NOME -------MARY MARY TELEFONE -------1234-5678 2222-3333
114
57
Mtodos
! ! !
Funes ou procedimentos que modelam o comportamento dos objetos Armazenados no banco de dados atravs de PL/SQL ou Java Podem ser classificados em
" Membros " Estticos " Construtores " Comparao
115
Mtodos Membros
Forma como aplicaes acessam os dados dos objetos ! Possui sempre parmetro implcito SELF, logo trabalha com os atributos de um objeto especfico (1 tupla) ! chamado da seguinte forma:
!
OBJETO.METODO()
116
58
117
Mtodos Estticos
!
Mtodos de classe
" Trabalham
com dados globais do tipo do objeto e no com o objeto especfico " No possuem o parmetro SELF " chamado da seguinte forma: TIPO.METODO()
118
59
119
Mtodos Construtores
Responsvel por criar o objeto e instanciar seus atributos ! Definido pelo sistema ! Existente em todos os tipos de objeto
!
P = T_PESSOA(Marta Mattoso, 2562-8694, 28/01/1970)
120
60
Mtodos de Comparao
!
Para comparar dois objetos de tipos criados pelo usurio, o mesmo deve criar uma ordenao para o tipo usando mtodos de mapeamento (map methods) ou mtodos de ordenao (order methods) Recurso que possibilita a indexao de valores de tipos estruturados criados pelo usurio
121
Mtodos de Mapeamento
!
Produzem um nico valor de um tipo predefinido (DATE, NUMBER, VARCHAR) para ser utilizado como comparao Toda comparao do tipo >, <, =, etc. ou DISTINCT, GROUP BY, ORDER BY chama automaticamente este mtodo de mapeamento, por isto que somente um mtodo deste tipo (ou de ordenao) pode ser declarado por tipo de objeto
122
61
123
Mtodos de Ordenao
! !
So mais gerais que os mtodos de mapeamento uma funo com um parmetro declarado para outro objeto do mesmo tipo e retorna:
" <0,
caso o objeto SELF seja menor que o parmetro " 0, caso sejam iguais " >0, caso o objeto SELF seja menor que o parmetro
124
62
125
63
Herana
!
e propriedade da substituio " Controle do usurio sobre a definio de tipos e mtodos herdveis
!
! !
Herana
! !
O Oracle implementa herana simples, ou seja, um subtipo pode ter apenas um supertipo Pode se especializar os atributos e mtodos de um supertipo da seguinte maneira:
" Adicionar
novos atributos " Adicionar novos mtodos " Modificar a implementao de alguns mtodos
128
64
Para permitir que um tipo possa possuir subtipos este deve ser definido como NOT FINAL. Por default um tipo de objeto FINAL.
CREATE TYPE T_PESSOA AS OBJECT ( NOME VARCHAR2(30), TELEFONES T_TELEFONES, DATA_NASCIMENTO DATE, ... ) NOT FINAL;
129
Para permitir que um mtodo no possa ser sobrescrito nos subtipos este deve ser declarado como FINAL. Ao contrrio de tipos de objetos, por default, um mtodo NOT FINAL.
CREATE TYPE T_PESSOA AS OBJECT ( NOME VARCHAR2(30), TELEFONES T_TELEFONES, FINAL MEMBER FUNCTION GET_NOME RETURN VARCHAR, ... ) NOT FINAL;
130
65
Criando Subtipos
CREATE TYPE T_ALUNO UNDER T_PESSOA ( DRE VARCHAR2(15), ... );
131
132
66
Material do curso
http://www.cos.ufrj.br/~baiao
134
67