- 1.34 MB
- 2022-04-29 14:33:38 发布
- 1、本文档共5页,可阅读全部内容。
- 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
- 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
- 文档侵权举报电话:19940600175。
'Chapter22:Object-BasedDatabases
Chapter22:Object-BasedDatabasesComplexDataTypesandObjectOrientationStructuredDataTypesandInheritanceinSQLTableInheritanceArrayandMultisetTypesinSQLObjectIdentityandReferenceTypesinSQLImplementingO-RFeaturesPersistentProgrammingLanguagesComparisonofObject-OrientedandObject-RelationalDatabases
Object-RelationalDataModelsExtendtherelationaldatamodelbyincludingobjectorientationandconstructstodealwithaddeddatatypes.Allowattributesoftuplestohavecomplextypes,includingnon-atomicvaluessuchasnestedrelations.Preserverelationalfoundations,inparticularthedeclarativeaccesstodata,whileextendingmodelingpower.Upwardcompatibilitywithexistingrelationallanguages.
ComplexDataTypesMotivation:Permitnon-atomicdomains(atomicindivisible)Exampleofnon-atomicdomain:setofintegers,orsetoftuplesAllowsmoreintuitivemodelingforapplicationswithcomplexdataIntuitivedefinition:allowrelationswheneverweallowatomic(scalar)values—relationswithinrelationsRetainsmathematicalfoundationofrelationalmodelViolatesfirstnormalform.
ExampleofaNestedRelationExample:libraryinformationsystemEachbookhastitle,alist(array)ofauthors,Publisher,withsubfieldsnameandbranch,andasetofkeywordsNon-1NFrelationbooks
4NFDecompositionofNestedRelationSupposeforsimplicitythattitleuniquelyidentifiesabookInrealworldISBNisauniqueidentifierDecomposebooksinto4NFusingtheschemas:(title,author,position)(title,keyword)(title,pub-name,pub-branch)4NFdesignrequiresuserstoincludejoinsintheirqueries.
ComplexTypesandSQLExtensionsintroducedinSQL:1999tosupportcomplextypes:CollectionandlargeobjecttypesNestedrelationsareanexampleofcollectiontypesStructuredtypesNestedrecordstructureslikecompositeattributesInheritanceObjectorientationIncludingobjectidentifiersandreferencesNotfullyimplementedinanydatabasesystemcurrentlyButsomefeaturesarepresentineachofthemajorcommercialdatabasesystemsReadthemanualofyourdatabasesystemtoseewhatitsupports
StructuredTypesandInheritanceinSQLStructuredtypes(a.k.a.user-definedtypes)canbedeclaredandusedinSQLcreatetypeNameas(firstnamevarchar(20),lastnamevarchar(20))finalcreatetypeAddressas(streetvarchar(20),cityvarchar(20),zipcodevarchar(20))notfinalNote:finalandnotfinalindicatewhethersubtypescanbecreatedStructuredtypescanbeusedtocreatetableswithcompositeattributescreatetableperson(nameName,addressAddress,dateOfBirthdate)Dotnotationusedtoreferencecomponents:name.firstname
StructuredTypes(cont.)User-definedrowtypescreatetypePersonTypeas(nameName,addressAddress,dateOfBirthdate)notfinalCanthencreateatablewhoserowsareauser-definedtypecreatetablecustomerofCustomerTypeAlternativeusingunnamedrowtypes.createtableperson_r(namerow(firstnamevarchar(20),lastnamevarchar(20)),addressrow(streetvarchar(20),cityvarchar(20),zipcodevarchar(20)),dateOfBirthdate)
MethodsCanaddamethoddeclarationwithastructuredtype.methodageOnDate(onDatedate)returnsintervalyearMethodbodyisgivenseparately.createinstancemethodageOnDate(onDatedate)returnsintervalyearforCustomerTypebeginreturnonDate-self.dateOfBirth;endWecannowfindtheageofeachcustomer:selectname.lastname,ageOnDate(current_date)fromcustomer
ConstructorFunctionsConstructorfunctionsareusedtocreatevaluesofstructuredtypesE.g.createfunctionName(firstnamevarchar(20),lastnamevarchar(20))returnsNamebeginsetself.firstname=firstname;setself.lastname=lastname;endTocreateavalueoftypeName,weusenewName(‘John’,‘Smith’)NormallyusedininsertstatementsinsertintoPersonvalues(newName(‘John’,‘Smith),newAddress(’20MainSt’,‘NewYork’,‘11001’),date‘1960-8-22’);
TypeInheritanceSupposethatwehavethefollowingtypedefinitionforpeople:createtypePerson(namevarchar(20),addressvarchar(20))UsinginheritancetodefinethestudentandteachertypescreatetypeStudentunderPerson(degreevarchar(20),departmentvarchar(20))createtypeTeacherunderPerson(salaryinteger,departmentvarchar(20))Subtypescanredefinemethodsbyusingoverridingmethodinplaceofmethodinthemethoddeclaration
MultipleTypeInheritanceSQL:1999andSQL:2003donotsupportmultipleinheritanceIfourtypesystemsupportsmultipleinheritance,wecandefineatypeforteachingassistantasfollows:createtypeTeachingAssistantunderStudent,TeacherToavoidaconflictbetweenthetwooccurrencesofdepartmentwecanrenamethemcreatetypeTeachingAssistantunderStudentwith(departmentasstudent_dept),Teacherwith(departmentasteacher_dept)Eachvaluemusthaveamost-specifictype
TableInheritanceTablescreatedfromsubtypescanfurtherbespecifiedassubtablesE.g.createtablepeopleofPerson;createtablestudentsofStudentunderpeople;createtableteachersofTeacherunderpeople;TuplesaddedtoasubtableareautomaticallyvisibletoqueriesonthesupertableE.g.queryonpeoplealsoseesstudentsandteachers.Similarlyupdates/deletesonpeoplealsoresultinupdates/deletesonsubtablesTooverridethisbehaviour,use“onlypeople”inqueryConceptually,multipleinheritanceispossiblewithtablese.g.teaching_assistantsunderstudentsandteachersButisnotsupportedinSQLcurrentlySowecannotcreateaperson(tupleinpeople)whoisbothastudentandateacher
ConsistencyRequirementsforSubtablesConsistencyrequirementsonsubtablesandsupertables.Eachtupleofthesupertable(e.g.people)cancorrespondtoatmostonetupleineachofthesubtables(e.g.studentsandteachers)AdditionalconstraintinSQL:1999:Alltuplescorrespondingtoeachother(thatis,withthesamevaluesforinheritedattributes)mustbederivedfromonetuple(insertedintoonetable).Thatis,eachentitymusthaveamostspecifictypeWecannothaveatupleinpeoplecorrespondingtoatupleeachinstudentsandteachers
ArrayandMultisetTypesinSQLExampleofarrayandmultisetdeclaration:createtypePublisheras(namevarchar(20),branchvarchar(20));createtypeBookas(titlevarchar(20),author_arrayvarchar(20)array[10],pub_datedate,publisherPublisher,keyword-setvarchar(20)multiset);createtablebooksofBook;
CreationofCollectionValuesArrayconstructionarray[‘Silberschatz’,`Korth’,`Sudarshan’]Multisetsmultiset[‘computer’,‘database’,‘SQL’]Tocreateatupleofthetypedefinedbythebooksrelation:(‘Compilers’,array[`Smith’,`Jones’],newPublisher(`McGraw-Hill’,`NewYork’),multiset[`parsing’,`analysis’])Toinserttheprecedingtupleintotherelationbooksinsertintobooksvalues(‘Compilers’,array[`Smith’,`Jones’],newPublisher(`McGraw-Hill’,`NewYork’),multiset[`parsing’,`analysis’]);
QueryingCollection-ValuedAttributesTofindallbooksthathavetheword“database”asakeyword,selecttitlefrombookswhere‘database’in(unnest(keyword-set))WecanaccessindividualelementsofanarraybyusingindicesE.g.:Ifweknowthataparticularbookhasthreeauthors,wecouldwrite:selectauthor_array[1],author_array[2],author_array[3]frombookswheretitle=`DatabaseSystemConcepts’Togetarelationcontainingpairsoftheform“title,author_name”foreachbookandeachauthorofthebookselectB.title,A.authorfrombooksasB,unnest(B.author_array)asA(author)ToretainorderinginformationweaddawithordinalityclauseselectB.title,A.author,A.positionfrombooksasB,unnest(B.author_array)withordinalityasA(author,position)
UnnestingThetransformationofanestedrelationintoaformwithfewer(orno)relation-valuedattributesuscalledunnesting.E.g.selecttitle,Aasauthor,publisher.nameaspub_name,publisher.branchaspub_branch,K.keywordfrombooksasB,unnest(B.author_array)asA(author),unnest(B.keyword_set)asK(keyword)Resultrelationflat_books
NestingNestingistheoppositeofunnesting,creatingacollection-valuedattributeNestingcanbedoneinamannersimilartoaggregation,butusingthefunctioncolect()inplaceofanaggregationoperation,tocreateamultisetTonesttheflat_booksrelationontheattributekeyword:selecttitle,author,Publisher(pub_name,pub_branch)aspublisher,collect(keyword)askeyword_setfromflat_booksgroupbytitle,author,publisherTonestonbothauthorsandkeywords:selecttitle,collect(author)asauthor_set,Publisher(pub_name,pub_branch)aspublisher,collect(keyword)askeyword_setfromflat_booksgroupbytitle,publisher
Nesting(Cont.)Anotherapproachtocreatingnestedrelationsistousesubqueriesintheselectclause,startingfromthe4NFrelationbooks4selecttitle,array(selectauthorfromauthorsasAwhereA.title=B.titleorderbyA.position)asauthor_array,Publisher(pub-name,pub-branch)aspublisher,multiset(selectkeywordfromkeywordsasKwhereK.title=B.title)askeyword_setfrombooks4asB
Object-IdentityandReferenceTypesDefineatypeDepartmentwithafieldnameandafieldheadwhichisareferencetothetypePerson,withtablepeopleasscope:createtypeDepartment(namevarchar(20),headref(Person)scopepeople)WecanthencreateatabledepartmentsasfollowscreatetabledepartmentsofDepartmentWecanomitthedeclarationscopepeoplefromthetypedeclarationandinsteadmakeanadditiontothecreatetablestatement:createtabledepartmentsofDepartment(headwithoptionsscopepeople)Referencedtablemusthaveanattributethatstorestheidentifier,calledtheself-referentialattributecreatetablepeopleofPersonrefisperson_idsystemgenerated;
InitializingReference-TypedValuesTocreateatuplewithareferencevalue,wecanfirstcreatethetuplewithanullreferenceandthensetthereferenceseparately:insertintodepartmentsvalues(`CS’,null)updatedepartmentssethead=(selectp.person_idfrompeopleaspwherename=`John’)wherename=`CS’
UserGeneratedIdentifiersThetypeoftheobject-identifiermustbespecifiedaspartofthetypedefinitionofthereferencedtable,andThetabledefinitionmustspecifythatthereferenceisusergeneratedcreatetypePerson(namevarchar(20)addressvarchar(20))refusingvarchar(20)createtablepeopleofPersonrefisperson_idusergeneratedWhencreatingatuple,wemustprovideauniquevaluefortheidentifier:insertintopeople(person_id,name,address)values(‘01284567’,‘John’,`23CoyoteRun’)WecanthenusetheidentifiervaluewheninsertingatupleintodepartmentsAvoidsneedforaseparatequerytoretrievetheidentifier:insertintodepartmentsvalues(`CS’,`02184567’)
UserGeneratedIdentifiers(Cont.)Canuseanexistingprimarykeyvalueastheidentifier:createtypePerson(namevarchar(20)primarykey,addressvarchar(20))reffrom(name)createtablepeopleofPersonrefisperson_idderivedWheninsertingatuplefordepartments,wecanthenuseinsertintodepartmentsvalues(`CS’,`John’)
PathExpressionsFindthenamesandaddressesoftheheadsofalldepartments:selecthead–>name,head–>addressfromdepartmentsAnexpressionsuchas“head–>name”iscalledapathexpressionPathexpressionshelpavoidexplicitjoinsIfdepartmentheadwerenotareference,ajoinofdepartmentswithpeoplewouldberequiredtogetattheaddressMakesexpressingthequerymucheasierfortheuser
ImplementingO-RFeaturesSimilartohowE-RfeaturesaremappedontorelationschemasSubtableimplementationEachtablestoresprimarykeyandthoseattributesdefinedinthattableor,Eachtablestoresbothlocallydefinedandinheritedattributes
PersistentProgrammingLanguagesLanguagesextendedwithconstructstohandlepersistentdataProgrammercanmanipulatepersistentdatadirectlynoneedtofetchitintomemoryandstoreitbacktodisk(unlikeembeddedSQL)Persistentobjects:Persistencebyclass-explicitdeclarationofpersistencePersistencebycreation-specialsyntaxtocreatepersistentobjectsPersistencebymarking-makeobjectspersistentaftercreationPersistencebyreachability-objectispersistentifitisdeclaredexplicitlytobesoorisreachablefromapersistentobject
ObjectIdentityandPointersDegreesofpermanenceofobjectidentityIntraprocedure:onlyduringexecutionofasingleprocedureIntraprogram:onlyduringexecutionofasingleprogramorqueryInterprogram:acrossprogramexecutions,butnotifdata-storageformatondiskchangesPersistent:interprogram,pluspersistentacrossdatareorganizationsPersistentversionsofC++andJavahavebeenimplementedC++ODMGC++ObjectStoreJavaJavaDatabaseObjects(JDO)
PersistentC++SystemsExtensionsofC++languagetosupportpersistentstorageofobjectsSeveralproposals,ODMGstandardproposed,butnotmuchactionoflatepersistentpointers:e.g.d_Refcreationofpersistentobjects:e.g.new(db)T()Classextents:accesstoallpersistentobjectsofaparticularclassRelationships:RepresentedbypointersstoredinrelatedobjectsIssue:consistencyofpointersSolution:extensiontotypesystemtoautomaticallymaintainback-referencesIteratorinterfaceTransactionsUpdates:mark_modified()functiontotellsystemthatapersistentobjectthatwasfetchedintomemoryhasbeenupdatedQuerylanguage
PersistentJavaSystemsStandardforaddingpersistencetoJava:JavaDatabaseObjects(JDO)PersistencebyreachabilityBytecodeenhancementClassesseparatelydeclaredaspersistentBytecodemodifierprogrammodifiesclassbytecodetosupportpersistenceE.g.FetchobjectondemandMarkmodifiedobjectstobewrittenbacktodatabaseDatabasemappingAllowsobjectstobestoredinarelationaldatabaseClassextentsSinglereferencetypenodifferencebetweenin-memorypointerandpersistentpointerImplementationtechniquebasedonhollowobjects(a.k.a.pointerswizzling)
Object-RelationalMappingObject-RelationalMapping(ORM)systemsbuiltontopoftraditionalrelationaldatabasesImplementorprovidesamappingfromobjectstorelationsObjectsarepurelytransient,nopermanentobjectidentityObjectscanberetriedfromdatabaseSystemusesmappingtofetchrelevantdatafromrelationsandconstructobjectsUpdatedobjectsarestoredbackindatabasebygeneratingcorrespondingupdate/insert/deletestatementsTheHibernateORMsystemiswidelyuseddescribedinSection9.4.2ProvidesAPItostart/endtransactions,fetchobjects,etcProvidesquerylanguageoperatingdireclyonobjectmodelqueriestranslatedtoSQLLimitations:overheads,especiallyforbulkupdates
ComparisonofO-OandO-RDatabasesRelationalsystemssimpledatatypes,powerfulquerylanguages,highprotection.Persistent-programming-language-basedOODBscomplexdatatypes,integrationwithprogramminglanguage,highperformance.Object-relationalsystemscomplexdatatypes,powerfulquerylanguages,highprotection.Object-relationalmappingsystemscomplexdatatypesintegratedwithprogramminglanguage,butbuiltasalayerontopofarelationaldatabasesystemNote:ManyrealsystemsblurtheseboundariesE.g.persistentprogramminglanguagebuiltasawrapperonarelationaldatabaseoffersfirsttwobenefits,butmayhavepoorperformance.
EndofChapter22
Figure22.05
Figure22.07'
您可能关注的文档
- 数据结构课件PPT110章全 第六章 树和二叉树.ppt
- 数据结构课件PPT110章全 第七章 图.ppt
- 数据库系统概念全套配套课件PPT ch12.ppt
- 数据库系统概念全套配套课件PPT ch6.ppt
- 数据库系统概念全套配套课件PPT ch2.ppt
- 数据库系统概念全套配套课件PPT appB.ppt
- 数据库系统概念全套配套课件PPT ch16.ppt
- 数据库系统概念全套配套课件PPT ch7.ppt
- 数据库系统概念全套配套课件PPT ch26.ppt
- 数据库系统概念全套配套课件PPT ch23.ppt
- 数据库系统概念全套配套课件PPT ch21.ppt
- 数据库系统概念全套配套课件PPT ch15.ppt
- 土木工程材料第2版柯国军配套教学课件PPT 06土木工程材料.ppt
- 土木工程材料第2版柯国军配套教学课件PPT 01土木工程材料.ppt
- 土木工程材料第2版柯国军配套教学课件PPT 07土木工程材料.ppt
- 土木工程材料第2版柯国军配套教学课件PPT 14土木工程材料.ppt
- 土木工程材料第2版柯国军配套教学课件PPT 10土木工程材料.ppt
- 土木工程材料第2版柯国军配套教学课件PPT 09土木工程材料.ppt