Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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()
Possvel calcular oosalrio Possvel calcular salrio no nvel de Employee? no nvel de Employee?
Instructor totalCreditsSemester()
TA semesterSalary Salary()
21
Polimorfismo
Employee DateHired status Salary()
Objetos de diferentes Objetos de diferentes classes respondem mesma classes respondem mesma mensagem de diferentes maneiras mensagem de diferentes 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( int i = 0; i < Employees.length; i++ ){ for( int i = 0; i < Employees.length; i++ ){ e = Employees[i]; e = Employees[i]; System.out.println( e.name ); System.out.println( 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 Course class Course name: string, name: string, cno: integer cno: integer dept : Department dept : Department sections: list[CourseSection], sections: list[CourseSection], ... ? ... ?
43
Atributos simples
! !
string...
Dependendo da implementao, os tipos bsicos podem ser tratados Dependendo da implementao, os tipos bsicos podem ser tratados sintaticamente e semanticamente como objetos. Esta abordagem sintaticamente e semanticamente como objetos. Esta abordagem porm no vantajosa quanto a eficincia. porm no vantajosa quanto a 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 c courses 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 c.name select c.name select c.name from Course c, Department d, select c.name from Course c, Department d, from courses c Professor p from courses c Professor p where c.dept.chair.state = AM; where c.dept = d.dno where c.dept.chair.state = AM; where c.dept = d.dno and d.chair = p.id and d.chair = p.id and p.state = AM; and p.state = 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 c select c from courses c, from courses c, c.dept.students s c.dept.students s where s.city = Manaus; where s.city = Manaus;
SQL
select c.* select c.* from Course c, from Course c, Department d, Student s Department d, Student s where c.dept = d.dno where c.dept = d.dno and d.dno = s.majors and d.dno = s.majors and s.city = Manaus; and s.city = 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
d.*, s.name select struct (dept:d, std:s.name) select d.*, s.name select struct (dept:d, std:s.name) select Department d, from Department d, from from departments d, from departments d, Professor p, Student s Professor p, Student 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 s.advisor = p.id and s.advisor = p.id and p.name = Altigran; and p.name = 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 e.name, e.street, e.zip select e.name, e.street, e.zip from SQL from employees e employees e where e.DateHired > 2000; select e.name, e.street, e.zip where e.DateHired > 2000; select e.name, e.street, e.zip from from Staff e, Staff e, Employee where e.DateHired > 2000; where e.DateHired > 2000; DateHired UNION ALL status UNION ALL select e.name, e.street, e.zip select e.name, e.street, e.zip Salary() from from Professors e Professors e where e.DateHired > 2000; where e.DateHired > 2000; UNION ALL UNION ALL Staff Instructor select e.name, e.street, e.zip select e.name, e.street, e.zip annualSalary from from TA e TA e totalCreditsSemester() Salary() where e.DateHired > 2000; where e.DateHired > 2000;
Professor AYSalary monthSummer Salary() TA semesterSalary Salary()
73
Herana e associao
OQL
select e.name, e.street, e.zip select e.name, e.street, e.zip from employees ee from employees where e.DateHired >> 2000 where e.DateHired 2000 and e.worksin.budget >> 10k; and e.worksin.budget 10k;
SQL
select e.name, e.street, e.zip select e.name, e.street, e.zip from Staff e, Department dd from Staff e, Department where e.DateHired >> 2000 where e.DateHired 2000 and d. budget >> 10k and d. budget 10k and e.worksin == d.deptNo; and e.worksin d.deptNo; UNION ALL UNION ALL select e.name, e.street, e.zip select e.name, e.street, e.zip from Staff e, Department dd from Staff e, Department where e.DateHired >> 2000 where e.DateHired 2000 and d. budget >> 10k and d. budget 10k and e.worksin == d.deptNo; and e.worksin d.deptNo; UNION ALL UNION ALL select e.name, e.street, e.zip select e.name, e.street, e.zip from Staff e, Department dd from Staff e, Department where e.DateHired >> 2000 where e.DateHired 2000 and d. budget >> 10k and d. budget 10k and e.worksin == d.deptNo; and e.worksin 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 type Professor as( create type Professor as( name varchar(20), name varchar(20), AYsalary integer ) AYsalary integer ) method giveraise(percent integer) method giveraise(percent integer) create method giveraise(percent integer) for Professor create method giveraise(percent integer) for Professor begin begin set self.AYsalary = self.AYsalary + set self.AYsalary = self.AYsalary + (self.AYsalary * percent)/100; (self.AYsalary * percent)/100; end end
93
Tipos Complexos
!
Tipos Estruturados
" Valores
!
create function Department( n varchar(20), b varchar(20)) create function Department( n varchar(20), b varchar(20)) returns Department returns Department begin begin set name = n; set name = n; set cityName = b; set cityName = b; end end insert into Students values insert into Students values (Sarah, array[Dave,Linda], 17-oct-1970, (Sarah, array[Dave,Linda], 17-oct-1970, Department(computer Science, San Diego)) Department(computer Science, San 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 table People of Person create table People of Person create table Students of Student under People create table Students of Student under People create table Professors of Professors under Person create table Professors of Professors under 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 type Department( create type Department( name varchar(20), name varchar(20), cityName varchar(20, cityName varchar(20, chair ref(Professor) scope Professors) chair ref(Professor) scope Professors) create table Departments of Department create table Departments of Department insert into Departments values (Geology, San Diego, null) insert into Departments values (Geology, San Diego, null) update Departments update Departments set chair = ( select ref(p) from Professors as p set chair = ( select ref(p) from Professors as p where name = John) where name = John) where name = Geology where 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