對象序列化和持久化課件_第1頁
對象序列化和持久化課件_第2頁
對象序列化和持久化課件_第3頁
對象序列化和持久化課件_第4頁
對象序列化和持久化課件_第5頁
已閱讀5頁,還剩185頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

對象序列化和持久化ObjectSerializationandPersistence2022/12/22InstituteofComputerSoftwareNanjingUniversity1ObjectSerializationandPersi摘要對象序列化對象持久化LanguagelevelDatabasesHibernate2022/12/22InstituteofComputerSoftwareNanjingUniversity2摘要對象序列化2022/12/17Instituteof摘要對象序列化對象持久化LanguagelevelDatabasesHibernate2022/12/22InstituteofComputerSoftwareNanjingUniversity3摘要對象序列化2022/12/17Instituteof摘要對象序列化對象持久化LanguagelevelDatabasesHibernate2022/12/22InstituteofComputerSoftwareNanjingUniversity4摘要對象序列化2022/12/17InstituteofObjectSerializationWhyWhatHow2022/12/22InstituteofComputerSoftwareNanjingUniversity5ObjectSerializationWhy2022/12JavaObjectSerialization--WhySerializationisusedforlightweightpersistenceandforcommunicationviasocketsorRemoteMethodInvocation(RMI).2022/12/22InstituteofComputerSoftwareNanjingUniversity6JavaObjectSerialization--WJavaObjectSerialization--ExamplepublicclassClient{publicstaticvoidmain(Stringargs[]){try{//Createasocket Socketsoc=newSocket(InetAddress.getLocalHost(),8020); OutputStreamo=soc.getOutputStream(); ObjectOutputs=newObjectOutputStream(o); s.writeObject("Today'sdate"); s.writeObject(newDate());

s.flush();s.close();}catch(Exceptione){System.out.println(e.getMessage());System.out.println("Errorduringserialization"); System.exit(1);}}}2022/12/22InstituteofComputerSoftwareNanjingUniversity7JavaObjectSerialization--EJavaObjectSerialization--ExamplepublicclassServer{publicstaticvoidmain(Stringargs[]){ServerSocketser=null;Socketsoc=null;Stringstr=null;Dated=null;try{ ser=newServerSocket(8020); soc=ser.accept(); InputStreamo=soc.getInputStream(); ObjectInputs=newObjectInputStream(o);

str=(String)s.readObject(); d=(Date)s.readObject(); s.close(); System.out.println(str); System.out.println(d);}catch(Exceptione){ System.out.println(e.getMessage()); System.out.println("Errorduringserialization"); System.exit(1);}}}2022/12/22InstituteofComputerSoftwareNanjingUniversity8JavaObjectSerialization--EJavaObjectSerialization--ExampleWritingtoanobjectstream2022/12/22InstituteofComputerSoftwareNanjingUniversity9//Serializetoday'sdatetoafile.FileOutputStreamf=newFileOutputStream("tmp");ObjectOutputs=newObjectOutputStream(f);s.writeObject("Today");s.writeObject(newDate());s.flush();JavaObjectSerialization--EJavaObjectSerialization--ExampleReadingfromanobjectstream2022/12/22InstituteofComputerSoftwareNanjingUniversity10//Deserializeastringanddatefromafile.FileInputStreamin=newFileInputStream("tmp");ObjectInputStreams=newObjectInputStream(in);Stringtoday=(String)s.readObject();Datedate=(Date)s.readObject();JavaObjectSerialization--EJavaObjectSerialization--WhatObjectSerializationextendsthecoreJavaInput/Outputclasseswithsupportforobjects.ObjectSerializationsupportstheencodingofobjects,andtheobjectsreachablefromthem,intoastreamofbytes;anditsupportsthecomplementaryreconstructionoftheobjectgraphfromthestream.2022/12/22InstituteofComputerSoftwareNanjingUniversity11JavaObjectSerialization--WJavaObjectSerialization--GoalHaveasimpleyetextensiblemechanism.MaintaintheJavaobjecttypeandsafetypropertiesintheserializedform.Beextensibletosupportmarshalingandunmarshalingasneededforremoteobjects.BeextensibletosupportsimplepersistenceofJavaobjects.Requireperclassimplementationonlyforcustomization.Allowtheobjecttodefineitsexternalformat.2022/12/22InstituteofComputerSoftwareNanjingUniversity12JavaObjectSerialization--GJavaObjectSerialization--HowObjectstobesavedinthestreammaysupporteithertheSerializableortheExternalizableinterface.ForSerializableobjects,thestreamincludessufficientinformationtorestorethefieldsinthestreamtoacompatibleversionoftheclass.ForExternalizableobjects,theclassissolelyresponsiblefortheexternalformatofitscontents.2022/12/22InstituteofComputerSoftwareNanjingUniversity13JavaObjectSerialization--HTheSerializableInterfacepublicinterfacejava.io.Serializable{};ASerializableclassmustdothefollowing:Implementthejava.io.SerializableinterfaceIdentifythefieldsthatshouldbeserializableHaveaccesstotheno-argconstructorofitsfirstnonserializablesuperclass2022/12/22InstituteofComputerSoftwareNanjingUniversity14TheSerializableInterfacepublTheSerializableInterfaceTheclasscanoptionallydefinethefollowingmethods:writeObject(ObjectOutputStream)readObject(ObjectInputStream)writeReplace()readResolve()2022/12/22InstituteofComputerSoftwareNanjingUniversity15思考:如果一個可序列化的類實現(xiàn)了以上四個方法,那么在序列化和反序列化的過程中,這幾個方法的調用次序如何?TheSerializableInterfaceTheTheExternalizableInterfacepublicinterfaceExternalizableextendsSerializable{ publicvoidwriteExternal(ObjectOutputout) throwsIOException; publicvoidreadExternal(ObjectInputin)throwsIOException,java.lang.ClassNotFoundException;}2022/12/22InstituteofComputerSoftwareNanjingUniversity16TheExternalizableInterfacepuTheExternalizableInterfaceTheclassofanExternalizableobjectmustdothefollowing:Implementthejava.io.ExternalizableinterfaceImplementawriteExternalmethodtosavethestateoftheobjectImplementareadExternalmethodtoreadthedatawrittenbythewriteExternalmethodfromthestreamandrestorethestateoftheobjectHavethewriteExternalandreadExternalmethodsbesolelyresponsiblefortheformat,ifanexternallydefinedformatiswrittenHaveapublicno-argconstructor2022/12/22InstituteofComputerSoftwareNanjingUniversity17TheExternalizableInterfaceThTheExternalizableInterfaceAnExternalizableclasscanoptionallydefinethefollowingmethods:writeReplacereadResolve2022/12/22InstituteofComputerSoftwareNanjingUniversity18Note:聲明類實現(xiàn)Externalizable接口會有重大的安全風險。writeExternal()與readExternal()方法聲明為public,惡意類可以用這些方法讀取和寫入對象數(shù)據(jù)。如果對象包含敏感信息,則要格外小心。TheExternalizableInterfaceAn區(qū)別Serializable自動存儲必要信息,用以反序列化被存儲的實例優(yōu)點內建支持易于實現(xiàn)缺點占用空間過大速度慢Externalizable只保存被存儲的類的標識,完全由程序員完成讀取和寫入工作優(yōu)點開銷較少可能的速度提升缺點虛擬機不提供幫助,程序員負擔重2022/12/2219InstituteofComputerSoftwareNanjingUniversity區(qū)別SerializableExternalizable20serialVersionUIDprivate

static

final

long

serialVersionUIDForcompabilityInvalidClassExceptionItisstronglyrecommendedthatallserializableclassesexplicitlydeclareserialVersionUIDvaluesserialver;eclipse2022/12/22InstituteofComputerSoftwareNanjingUniversity20serialVersionUIDprivatestaticSerializationPrinciples如果該類有父類如果父類實現(xiàn)了可序列化接口,則OK如果父類沒有實現(xiàn)可序列化接口,則父類所有字段的屬性默認情況下不會被序列化如果該類的某個屬性標識為static類型的,則該屬性不能序列化;如果該類的某個屬性采用transient關鍵字標識,則該屬性不能序列化;2022/12/22InstituteofComputerSoftwareNanjingUniversity21SerializationPrinciples如果該類有父SerializationPrinciples在我們標注一個類可以序列化的時候,其以下屬性應該設置為transient來避免序列化:線程相關的屬性;需要訪問IO、本地資源、網絡資源等的屬性;沒有實現(xiàn)可序列化接口的屬性;2022/12/22InstituteofComputerSoftwareNanjingUniversity22SerializationPrinciples在我們標注一SomeItemsfrom《EffectiveJava》2022/12/22InstituteofComputerSoftwareNanjingUniversity23SomeItemsfrom《EffectiveJavEffectiveJavaforSerialization1.ImplementSerializablejudiciously謹慎地實現(xiàn)Serializable代價1:一旦一個類被發(fā)布,則“改變這個類的實現(xiàn)”的靈活性將大大降低。序列化會使類的演化受到限制。代價2:增加了錯誤和安全漏洞的可能性。序列化機制是一種語言之外的對象創(chuàng)建機制。代價3:隨著一個類的新版本的發(fā)行,相關的測試負擔增加了??尚蛄谢惖淖兓酱?,它就越需要測試。2022/12/22InstituteofComputerSoftwareNanjingUniversity24EffectiveJavaforSerializatiEffectiveJavaforSerializationNotes:為了繼承而設計的類應該很少實現(xiàn)Serializable,接口也應該很少會擴展它。對于為繼承而設計的不可序列化的類,應該考慮提供一個無參數(shù)的構造函數(shù)。內部類應該很少實現(xiàn)Serializable。2022/12/22InstituteofComputerSoftwareNanjingUniversity25EffectiveJavaforSerializatiEffectiveJavaforSerialization2.Considerusingacustomserializedform考慮使用自定義的序列化形式如果一個對象的物理表示等同于它的邏輯內容,則默認的序列化形式可能是合適的。即使確定了默認序列化形式是合適的,通常仍然要提供一個readObject方法以保證約束關系和安全性。2022/12/22InstituteofComputerSoftwareNanjingUniversity26EffectiveJavaforSerializatiEffectiveJavaforSerialization2022/12/22InstituteofComputerSoftwareNanjingUniversity27EffectiveJavaforSerializatiEffectiveJavaforSerialization2022/12/22InstituteofComputerSoftwareNanjingUniversity28EffectiveJavaforSerializatiEffectiveJavaforSerialization當一個對象的物理表示與它的邏輯數(shù)據(jù)內容有實質性的區(qū)別時,使用默認序列化形式有4個缺點:它使這個類的導出API永久地束縛在該類的內部表示上。它要消耗過多的空間。它要消耗過多的時間。它會引起棧溢出。2022/12/22InstituteofComputerSoftwareNanjingUniversity29EffectiveJavaforSerializati2022/12/22InstituteofComputerSoftwareNanjingUniversity302022/12/17InstituteofComputeEffectiveJavaforSerialization2022/12/22InstituteofComputerSoftwareNanjingUniversity31EffectiveJavaforSerializatiEffectiveJavaforSerialization如果所有的實例域都是transient的,那么省去調用defaultWriteObject和defaultReadObject也是允許的,但是不推薦這樣做。在決定將一個域做成非transient之前,請一定要確信它的值將是該對象邏輯狀態(tài)的一部分。不管你選擇了哪種序列化形式,你都要為自己編寫的每個序列化的類聲明一個顯式的序列化版本UID。2022/12/22InstituteofComputerSoftwareNanjingUniversity32privatestaticfinallongserialVersionID=randomLongValueEffectiveJavaforSerializatiEffectiveJavaforSerialization3.WritereadObjectmethodsdefensively保護性地編寫readObject方法readObject方法實際上相當于另一個共有的構造函數(shù),如同其他構造函數(shù)一樣,它也要求所有同樣的注意事項:檢查實參的有效性,并且必要時對參數(shù)進行保護性拷貝。2022/12/22InstituteofComputerSoftwareNanjingUniversity33EffectiveJavaforSerializatiVersioningVersioningraisessomefundamentalquestionsabouttheidentityofaclass,includingwhatconstitutesacompatiblechange.Acompatiblechange

isachangethatdoesnotaffectthecontractbetweentheclassanditscallers.2022/12/22InstituteofComputerSoftwareNanjingUniversity34VersioningVersioningraisessoIncompatiblechangesDeletingfieldsMovingclassesupordownthehierarchyChanginganonstaticfieldtostaticoranontransientfieldtotransientChangingthedeclaredtypeofaprimitivefieldChangingthewriteObjectorreadObjectmethodsothatitnolongerwritesorreadsthedefaultfielddataorchangingitsothatitattemptstowriteitorreaditwhenthepreviousversiondidnot.2022/12/22InstituteofComputerSoftwareNanjingUniversity35IncompatiblechangesDeletingfIncompatiblechangesChangingaclassfromSerializabletoExternalizableorviceversaChangingaclassfromanon-enumtypetoanenumtypeorviceversaRemovingeitherSerializableorExternalizableAddingthewriteReplaceorreadResolvemethodtoaclassisincompatibleifthebehaviorwouldproduceanobjectthatisincompatiblewithanyolderversionoftheclass.2022/12/22InstituteofComputerSoftwareNanjingUniversity36IncompatiblechangesChangingaCompatiblechangesAddingfieldsAddingclassesRemovingclassesAddingwriteObject/readObjectmethodsRemovingwriteObject/readObjectmethodsAddingjava.io.SerializableChangingtheaccesstoafieldChangingafieldfromstatictononstaticortransienttonontransient2022/12/22InstituteofComputerSoftwareNanjingUniversity37CompatiblechangesAddingfield摘要對象序列化對象持久化LanguagelevelDatabasesHibernate2022/12/22InstituteofComputerSoftwareNanjingUniversity38摘要對象序列化2022/12/17Instituteof摘要對象序列化對象持久化LanguagelevelDatabasesHibernate2022/12/22InstituteofComputerSoftwareNanjingUniversity39摘要對象序列化2022/12/17InstituteofObjectPersistenceDuringexecutionofapplication:objectsarecreatedandmanipulatedWhathappenstoobjectsaftertermination?VariouskindsofobjectsTransientobjects:DisappearwithcurrentsessionPersistentobjects:StayaroundfromsessiontosessionMaybesharedwithotherapplications(e.g.databases)2022/12/22InstituteofComputerSoftwareNanjingUniversity40ObjectPersistenceDuringexecuApproachestomanipulatepersistentobjectsPersistencemechanismsfromprogramminglanguagesRelationaldatabasesObject-orienteddatabases2022/12/22InstituteofComputerSoftwareNanjingUniversity41ApproachestomanipulatepersiPersistencefromprogramminglanguagesMechanismsforstoringobjectsinfilesandretrievingthemSimpleobjects:egers,charactersconventionalmethodsusableCompositeobjects:containreferencestootherobjectsPersistenceClosureprinciple:Anystorageandretrievalmechanismmusthandletheobjectandallitsdependents.otherwise:danglingreferences2022/12/22InstituteofComputerSoftwareNanjingUniversity42Persistencefromprogrammingl對象結構的存儲與提取對象持久化的難點之一:對象之間的引用2022/12/22InstituteofComputerSoftwareNanjingUniversity43對象結構的存儲與提取對象持久化的難點之一:2022/12/1對象結構的存儲與提取需持久化整個對象引用閉包PersistenceclosureJava的serialization規(guī)則缺省規(guī)則:非static非transient的數(shù)據(jù)成員用戶定義classListimplementsSerializable{ Listnext; privatestaticfinalObjectStreamField[]serialPersistentFields=

{newObjectStreamField("next",List.class)};}2022/12/22InstituteofComputerSoftwareNanjingUniversity44對象結構的存儲與提取需持久化整個對象引用閉包2022/12/對象結構的存儲與提取閉包可能太大小對象引用(共享的)大對象2022/12/22InstituteofComputerSoftwareNanjingUniversity45對象結構的存儲與提取閉包可能太大2022/12/17Inst對象結構的存儲與提取Java的transient修飾子Transientfields不被序列化Staticfields也不被序列化開發(fā)者負責維護2022/12/22InstituteofComputerSoftwareNanjingUniversity46對象結構的存儲與提取Java的transient修飾子SchemaevolutionFact:ClasseschangeProblem:ObjectsarestoredofwhichclassdescriptionshavechangedSchemaevolution:Atleastoneclassusedbytheretrievingsystemdiffersfromitscounterpartstoredbythestoringsystem.Objectretrievalmismatch(Objectmismatch):Theretrievingsystemretrievesaparticularobjectwhoseowngeneratingclasswasdifferentinthestoringsystem.Nofullysatisfactorysolution2022/12/22InstituteofComputerSoftwareNanjingUniversity47SchemaevolutionFact:ClassesDifferentapproachesNaive,extremeapproaches:ForsakepreviouslystoredobjectsOveramigrationpathfromoldformattonewaone-time,enmasseconversionofoldobjectsnotapplicabletoalargepersistentstoreortoonethatmustbeavailablecontinuouslyMostgeneralsolution:On-the-flyconversionNote:Wecoveronlytheretrievalpart.Whethertowritebacktheconvertedobjectisaseparateissue.2022/12/22InstituteofComputerSoftwareNanjingUniversity48DifferentapproachesNaive,extOn-the-flyobjectconversionThreeseparateissues:Detection:CatchobjectmismatchNotification:MakeretrievingsystemawareofobjectmismatchCorrection:BringmismatchedobjecttoaconsistentstateMakeitacorrectinstanceofthenewclassversion2022/12/22InstituteofComputerSoftwareNanjingUniversity49On-the-flyobjectconversionThDetectionDetectamismatchbetweentwoversionsofanobject’sgeneratingclassTwocategoriesofdetectionpolicy:Nominalapproach:EachclassversionhasaversionnameCentralregistrationmechanismnecessaryStructuralapproach:DeduceclassdescriptorfromactualclassstructureStoreclassdescriptorSimpledetection:compareclassdescriptorsofretrievedobjectwithnewclassdescriptor2022/12/22InstituteofComputerSoftwareNanjingUniversity50DetectionDetectamismatchbetDetection:StructuralApproachWhatdoestheclassdescriptorneedtocontain?Trade-offbetweenefficiencyandreliabilityTwoextremeapproaches:C1:classnameC2:entireclasstext(e.g.abstractsyntaxtree)Reasonableapproaches:C3:classname,listofattributes(nameandtype)C4:inadditiontoC3:classinvariant2022/12/22InstituteofComputerSoftwareNanjingUniversity51Detection:StructuralApproachNotificationWhathappenswhenthedetectionmechanismhascaughtanobjectmismatch?LanguagelevelmechanismClassANYcouldincludeaprocedure: correct_mismatch

is

--Handleobjectretrievalmismatch.

local

exception:EXCEPTIONS

do

create

exception

exception.raise(‘‘[ Routinefailure:Object mismatchduringretrieval ]’’)

end2022/12/22InstituteofComputerSoftwareNanjingUniversity52NotificationWhathappenswhenCorrectionHowdowecorrectanobjectthatcausedamismatch?Currentsituation:Retrievalmechanismhascreatedanewobject(deducedfromastoredobjectwithsamegeneratingclass)Amismatchhasbeendetectednewobjectisintemporary(maybeinconsistent)state2022/12/22InstituteofComputerSoftwareNanjingUniversity53CorrectionHowdowecorrectanCorrection增加attribute刪除attribute2022/12/22InstituteofComputerSoftwareNanjingUniversity540.0Attributewasnotinstoredversion.FieldisinitializedtodefaultvalueofattributetypeStoredversionhadafield.Newversionhasremovedattribute.Attributeshavenotchanged.Correction2022/12/17InstituteCorrectioncorrect_mismatch

is

--Handleobjectretrievalmismatch --bycorrectlysettingupbalance.

do

balance:=deposits.total-withdrawals.total

ensure

consistent:balance=deposits.total-withdrawals.total

end2022/12/22InstituteofComputerSoftwareNanjingUniversity55depositswithdrawalsbalance0.0900100200240300newfield(initializedtodefaultvalue)oldfieldsWrong!維護不變式Correction2022/12/17Institute自動對象轉換:JavaserialVersionUID自動定義(根據(jù)類文件生成)1.Classname2.Theclassmodifiers3.Thenameofeachinterface

4.Foreachfieldoftheclass(exceptprivatestaticandprivatetransientfields):ThenameofthefieldThemodifiersofthefieldThedescriptorofthefield5.Foreachmethodincludingconstructors,exceptprivatemethodsandconstructors:ThenameofthemethodThemodifiersofthemethodThedescriptorofthemethod2022/12/22InstituteofComputerSoftwareNanjingUniversity56自動對象轉換:JavaserialVersionUID20自動對象轉換:Java手工指定ANY-ACCESS-MODIFIERstaticfinallongserialVersionUID=42L;類改變時仍然能夠反序列化Java定義了一些“兼容”條件,符合條件的自動轉換可以容忍的:addingfields,etc.太糟糕的:“Changingthetypeofafield”,deletingfields,etc2022/12/22InstituteofComputerSoftwareNanjingUniversity57自動對象轉換:Java手工指定2022/12/17Insti對于實在“糟糕”的類修改可以定制序列化和反序列化方法

privatevoidreadObject(ObjectInputStreamin){} privatevoidwriteObject(ObjectOutputStreamout){}2022/12/22InstituteofComputerSoftwareNanjingUniversity58對于實在“糟糕”的類修改可以定制序列化和反序列化方法2022摘要對象序列化對象持久化LanguagelevelDatabasesHibernate2022/12/22InstituteofComputerSoftwareNanjingUniversity59摘要對象序列化2022/12/17Instituteof對象持久化與數(shù)據(jù)庫Deficiencyoflanguagelevelmechanismsthereisonlyoneentryobject;thereisnosupportforcontent-basedqueries;eachcalltoretrievedre-createstheentirestructure,withnosharingofobjectsbetweensuccessivecalls;thereisnosupportforlettingdifferentclientapplicationsaccessthesamepersistentdatasimultaneouslyafull-fledgedsolutionrequirestakingadvantageofdatabasetechnology2022/12/22InstituteofComputerSoftwareNanjingUniversity60對象持久化與數(shù)據(jù)庫Deficiencyoflanguag對象持久化與數(shù)據(jù)庫AsetofmechanismsforstoringandretrievingdataitemsisaDBMSifitsupportsthefollowingitems:PersistenceProgrammablestructureArbitrarysizeAccesscontrolProperty-basedqueryingIntegrityconstraintsAdministrationSharingLockingTransactions2022/12/22InstituteofComputerSoftwareNanjingUniversity61自然地,要用數(shù)據(jù)庫來存儲持久化對象對象持久化與數(shù)據(jù)庫Asetofmechanismsf對象持久化與數(shù)據(jù)庫關系型數(shù)據(jù)庫:數(shù)據(jù)庫的主流Arelationaldatabaseisasetofrelations,eachcontainingasetoftuples(orrecords).關系代數(shù)Selection,Projection,Join2022/12/22InstituteofComputerSoftwareNanjingUniversity62對象持久化與數(shù)據(jù)庫關系型數(shù)據(jù)庫:數(shù)據(jù)庫的主流2022/12/對象持久化與數(shù)據(jù)庫Operations:relationalalgebra:selection,projection,joinQueries:standardizedlanguage(SQL)Usually“normalized”:everyfieldisasimplevalue;itcannotbeareference2022/12/22InstituteofComputerSoftwareNanjingUniversity63“TheCarterhouseofParma”“TheRedandtheBlack”Title“MadameBovary”“Eug?nieGrandet”date1830183918561833pages341307425346author“Stendahl”“Stendahl”“Flaubert”“Balzac”Relationbooks:fieldfieldname(=attribute)columntuple(=row)對象持久化與數(shù)據(jù)庫Operations:relationaOperationsSelection:date>1833ProjectionJoin2022/12/22InstituteofComputerSoftwareNanjingUniversity64“TheCarterhouseofParma”Title“MadameBovary”date18391856pages307425author“Stendahl”“Flaubert”O(jiān)perationsSelection:date>18OperationsSelectionProjection:onauthorJoin2022/12/22InstituteofComputerSoftwareNanjingUniversity65author“Stendahl”“Flaubert”“Balzac”O(jiān)perationsSelection2022/12/17IOperationsSelectionProjectionJoin:books

authors2022/12/22InstituteofComputerSoftwareNanjingUniversity66“TheCarterhouseofParma”“TheRedandtheBlack”Title“MadameBovary”“Eug?nieGrandet”date1830183918561833pages341307425346author“Stendahl”“Stendahl”“Flaubert”“Balzac”realname“HenriBeyle”“HenriBeyle”“GustaveFlaubert”“Honor?deBalzac”birth1783178318211799death1842184218801850name“Stendahl”“Stendahl”“Flaubert”“Balzac”realname“HenriBeyle”“HenriBeyle”“GustaveFlaubert”“Honor?deBalzac”birth1783178318211799death1842184218801850Relationauthors:OperationsSelection2022/12/17IUsingrelationaldatabaseswithO-OsoftwareComparisonofterms:Classlibrarytoprovideoperations(correspondingtoembeddedSQL).e.g.JDBC2022/12/22InstituteofComputerSoftwareNanjingUniversity67RelationalrelationtuplefieldnameO-OclassobjectattributeUsingrelationaldatabaseswitobject-relationalinteroperabilityAppropriateusagecases:Youarewritinganobject-orientedsystemwhichmustuseandpossiblyupdateexistingcorporatedata,storedinrelationaldatabases.YourO-Osoftwareneedstostoreobjectstructuressimpleenoughtofitnicelyintherelationalviewofthings.Otherwise,Impedancemismatch!2022/12/22InstituteofComputerSoftwareNanjingUniversity68object-relationalinteroperabiImpedanceMismatch關系數(shù)據(jù)庫數(shù)據(jù)結構規(guī)整,成員數(shù)目類型固定結構簡單,成員類型屬于一個既定小集合這些類型由大小固定的類型組合而成那么大小不定的域?表示對象引用的域?基于引用的間接查詢?繼承?更重要的是:對象identity語義2022/12/22InstituteofComputerSoftwareNanjingUniversity69ImpedanceMismatch關系數(shù)據(jù)庫2022/12Object-orienteddatabasesRemoveimpedancemismatchOvercomeconceptuallimitationsofrelationaldatabases:DatastructuremustberegularandsimpleSmallgroupofpredefinedtypesNormalforms:noreferencestoother“objects”Attempttooffermoreadvanceddatabasefacilities2022/12/22InstituteofComputerSoftwareNanjingUniversity70Object-orienteddatabasesRemovRequirementsforOODBsMinimalrequirements:DatabasefunctionalityEncapsulation:allowhidingtheinternalpropertiesofobjectsandmakethemaccessiblethroughanofficialinterfaceObjectidentity:associatewitheachobjectanidentificationthatisuniqueinthedatabaseReferences:allowanobjecttocontainreferencestootherobjects2022/12/22InstituteofComputerSoftwareNanjingUniversity71RequirementsforOODBsMinimalRequirementsforOODBsAdditionalrequirements:InheritanceTypingDynamicbindingObjectversioningSchemaevolutionLongtransactionsLockingObject-orientedqueries2022/12/22InstituteofComputerSoftwareNanjingUniversity72RequirementsforOODBsAdditionOODBsexamplesGemstoneItascaMatisseObjectivityObjectStoreOntosO2PoetMatisseVersantatETHZ:OMSPro2022/12/22InstituteofComputerSoftwareNanjingUniversity73OODBsexamplesGemstone2022/12/摘要對象序列化對象持久化LanguagelevelDatabasesHibernate2022/12/22InstituteofComputerSoftwareNanjingUniversity74摘要對象序列化2022/12/17Instituteof為什么需要對象持久化框架?OO中輕易實現(xiàn)的對象相同或相等,這樣的關系在關系數(shù)據(jù)庫中不存在。OO的一項核心特性是繼承,繼承很重要,因為它允許創(chuàng)建問題的精確模型,同時可以在層次結構中自上而下的共享屬性和行為。而關系數(shù)據(jù)庫不支持繼承的概念。對象之間可以輕易的實現(xiàn)一對一,一對多和多對多的關聯(lián)關系,而關系數(shù)據(jù)庫并不理解這些,它只知道外碼指向主碼。2022/12/22InstituteofComputerSoftwareNanjingUniversity75為什么需要對象持久化框架?OO中輕易實現(xiàn)的對象相同或相等,這對象持久化框架對象關系映射(ObjectRelationalMapping,簡稱ORM)是一種為了解決面向對象與關系數(shù)據(jù)庫存在的互不匹配的現(xiàn)象的技術。ORM是通過使用描述對象和數(shù)據(jù)庫之間映射的元數(shù)據(jù),將程序中的對象自動持久化到關系數(shù)據(jù)庫中。O/RMapper則指以O/R原理設計的持久化框架(Framework)hibernate,ibatis,jdo,etc.2022/12/22InstituteofComputerSoftwareNanjingUniversity76對象持久化框架對象關系映射(ObjectRelationa應用分層當前的現(xiàn)實:兩層結構三層結構N-層結構2022/12/22InstituteofComputerSoftwareNanjingUniversity77應用分層當前的現(xiàn)實:2022/12/17Institute2022/12/22InstituteofComputerSoftwareNanjingUniversity782022/12/17InstituteofComputeNoORM使用JDBC操作數(shù)據(jù)庫,業(yè)務處理邏輯和數(shù)據(jù)存取邏輯是混雜在一起的。一般基本都是如下幾個步驟:

1、建立數(shù)據(jù)庫連接,獲得Connection對象。

2、根據(jù)用戶的輸入組裝查詢SQL語句。

3、根據(jù)SQL語句建立Statement對象或者PreparedStatement對象。

4、用Connection對象執(zhí)行SQL語句,獲得結果集ResultSet對象。

5、然后一條一條讀取結果集ResultSet對象中的數(shù)據(jù)。

6、根據(jù)讀取到的數(shù)據(jù),按特定的業(yè)務邏輯進行計算。

7、根據(jù)計算得到的結果再組裝更新SQL語句。

8、再使用Connection對象執(zhí)行更新SQL語句,以更新數(shù)據(jù)庫中的數(shù)據(jù)。

9、最后依次關閉各個Statement對象和Connection對象。2022/12/22InstituteofComputerSoftwareNanjingUniversity79NoORM使用JDBC操作數(shù)據(jù)庫,業(yè)務處理邏輯和數(shù)據(jù)存NoORM優(yōu)點:運行效率高缺點:嵌入大量SQL語句,項目難以維護主要原因:業(yè)務處理邏輯和數(shù)據(jù)存取邏輯完全混雜在一塊2022/12/22InstituteofComputerSoftwareNanjingUniversity80NoORM優(yōu)點:運行效率高2022/12/17InstitHibernate它是連接Java應用程序和關系數(shù)據(jù)庫的中間件它對JDBCAPI進行了封裝,負責Java對象的持久化在分層的軟件架構中它位于持久化層,封裝了所有數(shù)據(jù)訪問細節(jié),使業(yè)務邏輯層可以專注于實現(xiàn)業(yè)務邏輯持久化層(PersistenceLayer),即專注于實現(xiàn)數(shù)據(jù)持久化應用領域的某個特定系統(tǒng)的一個邏輯層面,將數(shù)據(jù)使用者和數(shù)據(jù)實體相關聯(lián)它是一種ORM映射工具,能夠建立面向對象的域模型和關系數(shù)據(jù)模型之間的映射2022/12/22InstituteofComputerSoftwareNanjingUniversity81Hibernate它是連接Java應用程序和關系數(shù)據(jù)庫的中間2022/12/22InstituteofComputerSoftwareNanjingUniversity822022/12/17InstituteofCompute2022/12/22InstituteofComputerSoftwareNanjingUniversity832022/12/17InstituteofCompute對象-關系映射簡單映射將一個類中的一個數(shù)據(jù)成員定為關鍵字其它數(shù)據(jù)成員為屬性2022/12/22InstituteofComputerSoftwareNanjingUniversity84對象-關系映射簡單映射2022/12/17Institut2022/12/22InstituteofComputerSoftwareNanjingUniversity85packagede.laliluna.example;importjavax.persistence.Entity;importjavax.persistence.Id;importjavax.persistence.GeneratedValue;@EntitypublicclassHoney{@Id@GeneratedValue

privateIntegerid;

privateStringname;privateStringtaste;publicHoney(){}publicIntegergetId(){returnid;}publicvoidsetId(Integerid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){=name;}publicStringgetTaste(){returntaste;}publicvoidsetTaste(Stringtaste){this.taste=taste;}

@OverridepublicStringt

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論