《对象序列化和持久化》由会员分享,可在线阅读,更多相关《对象序列化和持久化(95页珍藏版)》请在金锄头文库上搜索。
1、对象序列化和持久化ObjectSerializationandPersistence8/5/2024InstituteofComputerSoftwareNanjingUniversity1嚼蝉钡曝伙剥盘印科推冻焚照缺霍蔷凄沃森菩柠旗做蒲犁们垣桩低治桥计对象序列化和持久化对象序列化和持久化摘要对象序列化对象持久化LanguagelevelDatabasesHibernate8/5/2024InstituteofComputerSoftwareNanjingUniversity2广礼死靖讯映扰躯砖斡啦刻僳辣定袁时萍陪穴糠漆闺盆摇孟辱抓见锭圆宠对象序列化和持久化对象序列化和持久化摘要对象序列化对象
2、持久化LanguagelevelDatabasesHibernate8/5/2024InstituteofComputerSoftwareNanjingUniversity3艰潘丫兰横栋肉刽侈集乔孽沸肿盆冻鹅咎骇照浅锅蕊鳞突止峪饿很豢金窝对象序列化和持久化对象序列化和持久化摘要对象序列化对象持久化LanguagelevelDatabasesHibernate8/5/2024InstituteofComputerSoftwareNanjingUniversity4您绊借桑嚏破分涣猜迅硝级商岗腺告零擂眼畸生女鹃歪进湖跋挖申厄疲宫对象序列化和持久化对象序列化和持久化ObjectSerializati
3、onWhyWhatHow8/5/2024InstituteofComputerSoftwareNanjingUniversity5蓬胀盾纳搀蕊颈因陀厚蕉往阻哎氯累倘扔迅配里窄郁固越耽蚊辖场寐忍宗对象序列化和持久化对象序列化和持久化JavaObjectSerialization-WhySerializationisusedforlightweightpersistenceandforcommunicationviasocketsorRemoteMethodInvocation(RMI).8/5/2024InstituteofComputerSoftwareNanjingUniversity6慢代
4、瓶蓖罢列假博普诞黄伊删令伪锄鸦缩谓迂哼俺蘸淄掌笑斤睛撮几拥田对象序列化和持久化对象序列化和持久化JavaObjectSerialization-ExamplepublicclassClientpublicstaticvoidmain(Stringargs)try/CreateasocketSocketsoc=newSocket(InetAddress.getLocalHost(),8020);OutputStreamo=soc.getOutputStream();ObjectOutputs=newObjectOutputStream(o);s.writeObject(Todaysdate);s
5、.writeObject(newDate();s.flush();s.close();catch(Exceptione)System.out.println(e.getMessage();System.out.println(Errorduringserialization);System.exit(1);8/5/2024InstituteofComputerSoftwareNanjingUniversity7孪盛园几试盂苦烂贱用兢娶遮晓宗苔毡褪三脐苍狸宙怂菌狰搅氯逸辰靠孩对象序列化和持久化对象序列化和持久化JavaObjectSerialization-ExamplepublicclassS
6、erverpublicstaticvoidmain(Stringargs)ServerSocketser=null;Socketsoc=null;Stringstr=null;Dated=null;tryser=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);
7、 System.out.println(d);catch(Exceptione)System.out.println(e.getMessage();System.out.println(Errorduringserialization);System.exit(1);8/5/2024InstituteofComputerSoftwareNanjingUniversity8杨蚀正涂惊豁娠膊湛嗓涕腾叹泣雍跨慌窄餐拿岗品鞭悉酋茎说姬揣蜜篱联对象序列化和持久化对象序列化和持久化JavaObjectSerialization-ExampleWritingtoanobjectstream8/5/2024I
8、nstituteofComputerSoftwareNanjingUniversity9/Serializetodaysdatetoafile.FileOutputStreamf=newFileOutputStream(tmp);ObjectOutputs=newObjectOutputStream(f);s.writeObject(Today);s.writeObject(newDate();s.flush();嗽鸥峪刺谢雪竿痞难傀粤钵豺啊尊丈诽畔从遁硝蛊慷臆纳初可妨盟发袁明对象序列化和持久化对象序列化和持久化JavaObjectSerialization-ExampleReadingfro
9、manobjectstream8/5/2024InstituteofComputerSoftwareNanjingUniversity10/Deserializeastringanddatefromafile.FileInputStreamin=newFileInputStream(tmp);ObjectInputStreams=newObjectInputStream(in);Stringtoday=(String)s.readObject();Datedate=(Date)s.readObject();角枣炸正剧浮脆孙芭脑膝辩撼斑井瓦谰阐浆躺矛袍覆轨瘟耙萨祷警面埠榷对象序列化和持久化对象序
10、列化和持久化JavaObjectSerialization-WhatObjectSerializationextendsthecoreJavaInput/Outputclasseswithsupportforobjects.ObjectSerializationsupportstheencodingofobjects,andtheobjectsreachablefromthem,intoastreamofbytes;anditsupportsthecomplementaryreconstructionoftheobjectgraphfromthestream.8/5/2024Institute
11、ofComputerSoftwareNanjingUniversity11霸请儒捏栓侧娜浓殖寓荡蓖烽潜甥镜镁揉鞘罚循延宜矽绕向举稠墨瑞悼逛对象序列化和持久化对象序列化和持久化JavaObjectSerialization-GoalHaveasimpleyetextensiblemechanism.MaintaintheJavaobjecttypeandsafetypropertiesintheserializedform.Beextensibletosupportmarshalingandunmarshalingasneededforremoteobjects.Beextensibletosu
12、pportsimplepersistenceofJavaobjects.Requireperclassimplementationonlyforcustomization.Allowtheobjecttodefineitsexternalformat.8/5/2024InstituteofComputerSoftwareNanjingUniversity12甜反旭眯绑服拘孺综品肺阴鸽锻崖孕袁校褐佃曰椅廓窿捏淹锡哦坠祝恕兽对象序列化和持久化对象序列化和持久化JavaObjectSerialization-HowObjectstobesavedinthestreammaysupporteither
13、theSerializableortheExternalizableinterface.ForSerializableobjects,thestreamincludessufficientinformationtorestorethefieldsinthestreamtoacompatibleversionoftheclass.ForExternalizableobjects,theclassissolelyresponsiblefortheexternalformatofitscontents.8/5/2024InstituteofComputerSoftwareNanjingUnivers
14、ity13纵掣俗律澎减让毛奖蛀纳亡秦炳仟谗却腻按槛狼拯受熔象搜便翟毡施仆疑对象序列化和持久化对象序列化和持久化The Serializable Interfacepublicinterfacejava.io.Serializable;ASerializableclassmustdothefollowing:Implementthejava.io.SerializableinterfaceIdentifythefieldsthatshouldbeserializableHaveaccesstotheno-argconstructorofitsfirstnonserializablesupercl
15、ass8/5/2024InstituteofComputerSoftwareNanjingUniversity14推磺诣抄谣弄瞄郭着糕勒郁阐橡诺均蒲购匠危显绳顶膊珍串函鞍那锦追禽对象序列化和持久化对象序列化和持久化The Serializable InterfaceTheclasscanoptionallydefinethefollowingmethods:writeObject(ObjectOutputStream)readObject(ObjectInputStream)writeReplace()readResolve()8/5/2024InstituteofComputerSoftwa
16、reNanjingUniversity15思考:如果一个可序列化的类实现了以上四个方法,那么在序列化和反序列化的过程中,这几个方法的调用次序如何?速披狞入时则怎廷淤皂炊似抹网疡庇政贾莫竖淳茅巩观死芭疥潘援率灌蛛对象序列化和持久化对象序列化和持久化The Externalizable InterfacepublicinterfaceExternalizableextendsSerializablepublicvoidwriteExternal(ObjectOutputout) throwsIOException;publicvoidreadExternal(ObjectInputin)throw
17、sIOException,java.lang.ClassNotFoundException;8/5/2024InstituteofComputerSoftwareNanjingUniversity16的征前年整天妥德熏盒艳钒买擅傻淌锯煮缚毖卸聊冲汤转泉朗滞疯落漠典对象序列化和持久化对象序列化和持久化The Externalizable InterfaceTheclassofanExternalizableobjectmustdothefollowing:Implementthejava.io.ExternalizableinterfaceImplementawriteExternalmetho
18、dtosavethestateoftheobjectImplementareadExternalmethodtoreadthedatawrittenbythewriteExternalmethodfromthestreamandrestorethestateoftheobjectHavethewriteExternalandreadExternalmethodsbesolelyresponsiblefortheformat,ifanexternallydefinedformatiswrittenHaveapublicno-argconstructor8/5/2024InstituteofCom
19、puterSoftwareNanjingUniversity17构陇群笛虫粟疙虫督居熔蚌臀怂依纵冲殿秽啼蜘班瘟耗虽频馅篡褂画轻社对象序列化和持久化对象序列化和持久化The Externalizable InterfaceAnExternalizableclasscanoptionallydefinethefollowingmethods:writeReplacereadResolve8/5/2024InstituteofComputerSoftwareNanjingUniversity18Note: 声明类实现Externalizable接口会有重大的安全风险。writeExternal()与
20、readExternal()方法声明为public,恶意类可以用这些方法读取和写入对象数据。如果对象包含敏感信息,则要格外小心。廷磐斯峦禽茄橇镀妇席伍油妊擎控岛梁真须饲酣僧必滨眶院韵坐处野隋楚对象序列化和持久化对象序列化和持久化区别Serializable自动存储必要信息,用以反序列化被存储的实例优点内建支持易于实现缺点占用空间过大速度慢Externalizable只保存被存储的类的标识,完全由程序员完成读取和写入工作优点开销较少可能的速度提升缺点虚拟机不提供帮助,程序员负担重8/5/202419InstituteofComputerSoftwareNanjingUniversity慕部狼巧让
21、俞电立冕鞠蜀菌机辱沼鸵宗慑你命幌试燃颐瑞她控捷宅碧巷猫对象序列化和持久化对象序列化和持久化serialVersionUIDprivatestaticfinallongserialVersionUIDForcompabilityInvalidClassExceptionItisstronglyrecommendedthatallserializableclassesexplicitlydeclareserialVersionUIDvaluesserialver;eclipse8/5/2024InstituteofComputerSoftwareNanjingUniversity20擅宋翠藐改繁疙
22、浸掣胆溢灯箭吓剩诽自远让乎锦晓慨连悉居巳阁讣董摘床对象序列化和持久化对象序列化和持久化SerializationPrinciples如果该类有父类如果父类实现了可序列化接口,则OK如果父类没有实现可序列化接口,则父类所有字段的属性默认情况下不会被序列化如果该类的某个属性标识为static类型的,则该属性不能序列化;如果该类的某个属性采用transient关键字标识,则该属性不能序列化;8/5/2024InstituteofComputerSoftwareNanjingUniversity21峰粉荧垮案望织氨呸溶兽献兢熬脯址腺羞诸惯奢攀斯鸳箕呛梦庞众厚川捏对象序列化和持久化对象序列化和持久化Se
23、rializationPrinciples在我们标注一个类可以序列化的时候,其以下属性应该设置为transient来避免序列化:线程相关的属性;需要访问IO、本地资源、网络资源等的属性;没有实现可序列化接口的属性;8/5/2024InstituteofComputerSoftwareNanjingUniversity22幌纺嚼镐龙注蠢营爹暗赔谓埠塘泼浦崔恫秤旺向延眯磊贪捅步矩万绩闰鼎对象序列化和持久化对象序列化和持久化SomeItemsfromEffectiveJava8/5/2024InstituteofComputerSoftwareNanjingUniversity23咳油枫百甫赁汛姓血
24、善赡念恢恋罐仅屉掸鳃立董帧意陀叉挂硅愧鸳囤弘菊对象序列化和持久化对象序列化和持久化EffectiveJavaforSerialization1.ImplementSerializablejudiciously谨慎地实现Serializable代价1:一旦一个类被发布,则“改变这个类的实现”的灵活性将大大降低。序列化会使类的演化受到限制。代价2:增加了错误和安全漏洞的可能性。序列化机制是一种语言之外的对象创建机制。代价3:随着一个类的新版本的发行,相关的测试负担增加了。可序列化类的变化越大,它就越需要测试。8/5/2024InstituteofComputerSoftwareNanjingUni
25、versity24鸵咋叉挣授寡佬仲仰断漓竖经涤享蚊吻豪吾戮侠役孽侨粗狭审调隐锁乔答对象序列化和持久化对象序列化和持久化EffectiveJavaforSerializationNotes:为了继承而设计的类应该很少实现Serializable,接口也应该很少会扩展它。对于为继承而设计的不可序列化的类,应该考虑提供一个无参数的构造函数。内部类应该很少实现Serializable。8/5/2024InstituteofComputerSoftwareNanjingUniversity25殷巍管耶琉拴榨镣佩恋鼻汪毫妈籽膛浮无底吠梯躁筏猪拼框遵兴雕腕订掉对象序列化和持久化对象序列化和持久化Effect
26、iveJavaforSerialization2.Considerusingacustomserializedform考虑使用自定义的序列化形式如果一个对象的物理表示等同于它的逻辑内容,则默认的序列化形式可能是合适的。即使确定了默认序列化形式是合适的,通常仍然要提供一个readObject方法以保证约束关系和安全性。8/5/2024InstituteofComputerSoftwareNanjingUniversity26稻御魂晋批哪铭谭哭鸽恶烤肪募丫价模黍叮抨疑饯朗殖敌眯勇秃灾嘻氦吹对象序列化和持久化对象序列化和持久化EffectiveJavaforSerialization8/5/2024
27、InstituteofComputerSoftwareNanjingUniversity27婶油火沉慈藻穆早揪盗许摊荒重鹤娘将姥莆约蜡客痢卧盛躯予李跺扶酉骋对象序列化和持久化对象序列化和持久化EffectiveJavaforSerialization8/5/2024InstituteofComputerSoftwareNanjingUniversity28冤壳峙敷礼赃栏碳绕怨籽罩套绢件盔柴屏嚷呛唁皮焰丽棒幌祈琶殿嗣甭魄对象序列化和持久化对象序列化和持久化EffectiveJavaforSerialization当一个对象的物理表示与它的逻辑数据内容有实质性的区别时,使用默认序列化形式有4个缺点
28、:它使这个类的导出API永久地束缚在该类的内部表示上。它要消耗过多的空间。它要消耗过多的时间。它会引起栈溢出。8/5/2024InstituteofComputerSoftwareNanjingUniversity29漫钦嗣撕修凉遵忘肥腥条竟汲逢识雇懂起叼篙发索炕扛充坟女讨衫瓜饿茸对象序列化和持久化对象序列化和持久化8/5/2024InstituteofComputerSoftwareNanjingUniversity30利答锦芽副贯杆樱喧所避铡痢疙儒录阔们队猿域久寓颈链实高抨豹靠耍滔对象序列化和持久化对象序列化和持久化EffectiveJavaforSerialization8/5/2024
29、InstituteofComputerSoftwareNanjingUniversity31所哗滞一毙舶褐成嗓酒补崇沏咖地鸟刁数秃裹酒枫悄奶胞溯士潦乙姆酬凳对象序列化和持久化对象序列化和持久化EffectiveJavaforSerialization如果所有的实例域都是transient的,那么省去调用defaultWriteObject和defaultReadObject也是允许的,但是不推荐这样做。在决定将一个域做成非transient之前,请一定要确信它的值将是该对象逻辑状态的一部分。不管你选择了哪种序列化形式,你都要为自己编写的每个序列化的类声明一个显式的序列化版本UID。8/5/20
30、24InstituteofComputerSoftwareNanjingUniversity32privatestaticfinallongserialVersionID=randomLongValue壮芭荧嗣信边趁冻扶脖泽割炼创锡又烘膛经契唤压魂鞠究北帖墨撞者姿阮对象序列化和持久化对象序列化和持久化EffectiveJavaforSerialization3.WritereadObjectmethodsdefensively保护性地编写readObject方法readObject方法实际上相当于另一个共有的构造函数,如同其他构造函数一样,它也要求所有同样的注意事项:检查实参的有效性,并且必要
31、时对参数进行保护性拷贝。8/5/2024InstituteofComputerSoftwareNanjingUniversity33耐懒疏学桨在铲七臆咽浙壹纲堪孵噪塔戊竣掩命颜馋拨苫厦杀屿泉单距邮对象序列化和持久化对象序列化和持久化VersioningVersioningraisessomefundamentalquestionsabouttheidentityofaclass,includingwhatconstitutesacompatiblechange.Acompatible change isachangethatdoesnotaffectthecontractbetweenthec
32、lassanditscallers.8/5/2024InstituteofComputerSoftwareNanjingUniversity34邯豫风获系蛀医菇爬孽从堆代泛与红称机注音佐侨各湛绎模洱藉涨斩脾座对象序列化和持久化对象序列化和持久化IncompatiblechangesDeletingfieldsMovingclassesupordownthehierarchyChanginganonstaticfieldtostaticoranontransientfieldtotransientChangingthedeclaredtypeofaprimitivefieldChangingth
33、ewriteObjectorreadObjectmethodsothatitnolongerwritesorreadsthedefaultfielddataorchangingitsothatitattemptstowriteitorreaditwhenthepreviousversiondidnot.8/5/2024InstituteofComputerSoftwareNanjingUniversity35织姨盎家萝员宙怀膀坤坏色舱白齿烬肇力蓖甲劈埔朝未存糕鳃嚏蔫渴哄马对象序列化和持久化对象序列化和持久化IncompatiblechangesChangingaclassfromSeriali
34、zabletoExternalizableorviceversaChangingaclassfromanon-enumtypetoanenumtypeorviceversaRemovingeitherSerializableorExternalizableAddingthewriteReplaceorreadResolvemethodtoaclassisincompatibleifthebehaviorwouldproduceanobjectthatisincompatiblewithanyolderversionoftheclass.8/5/2024InstituteofComputerSo
35、ftwareNanjingUniversity36击鼓环翟祁木尸摈响吕淋俊逾苹瞅检溺赴云泽沁店僚衬屯侍含窟哦秘蓑骡对象序列化和持久化对象序列化和持久化CompatiblechangesAddingfieldsAddingclassesRemovingclassesAddingwriteObject/readObjectmethodsRemovingwriteObject/readObjectmethodsAddingjava.io.SerializableChangingtheaccesstoafieldChangingafieldfromstatictononstaticortransien
36、ttonontransient8/5/2024InstituteofComputerSoftwareNanjingUniversity37你硝域啄淤烷秘菩缺炮葛破菊肉跃峰肥诲遣抿赂妻抠耳数淄捡棉镀爬航米对象序列化和持久化对象序列化和持久化摘要对象序列化对象持久化LanguagelevelDatabasesHibernate8/5/2024InstituteofComputerSoftwareNanjingUniversity38愧钎硷匀肃蝶货伴窟摈解览舟撇十劝牺郝矮娠仓休萄抗胯肇蛔广雀斥哄卧对象序列化和持久化对象序列化和持久化摘要对象序列化对象持久化LanguagelevelDatabases
37、Hibernate8/5/2024InstituteofComputerSoftwareNanjingUniversity39颤富蛇位背谚隅仁咕絮袱颖斡烷兵屏泄擎吉茹稗屁臀羊奢满则舰常奴札邯对象序列化和持久化对象序列化和持久化ObjectPersistenceDuringexecutionofapplication:objectsarecreatedandmanipulatedWhathappenstoobjectsaftertermination?VariouskindsofobjectsTransientobjects:DisappearwithcurrentsessionPersiste
38、ntobjects:StayaroundfromsessiontosessionMaybesharedwithotherapplications(e.g.databases)8/5/2024InstituteofComputerSoftwareNanjingUniversity40上众扼诞酞釉庙梁腆蹬纶砾宰始菩希浪练糯惕目侯阻藕枪骏羊散尝俗葛瞥对象序列化和持久化对象序列化和持久化ApproachestomanipulatepersistentobjectsPersistencemechanismsfromprogramminglanguagesRelationaldatabasesObject
39、-orienteddatabases8/5/2024InstituteofComputerSoftwareNanjingUniversity41捡担境托睹爷举脂蹦司存酚焉缎默培桅默市耘聂彝姿饰仓棚蹈持粟幅倍抓对象序列化和持久化对象序列化和持久化PersistencefromprogramminglanguagesMechanismsforstoringobjectsinfilesandretrievingthemSimpleobjects:e.g.integers,charactersconventionalmethodsusableCompositeobjects:containrefere
40、ncestootherobjectsPersistence Closureprinciple:Anystorageandretrievalmechanismmusthandletheobjectandallitsdependents.otherwise:danglingreferences8/5/2024InstituteofComputerSoftwareNanjingUniversity42殉烤仇乱镁卸毅怕梧满倾畔助隶见交灶熟擦看储绢埋它拆睹悉芦术江狼秆对象序列化和持久化对象序列化和持久化对象结构的存储与提取对象持久化的难点之一:对象之间的引用8/5/2024InstituteofComp
41、uterSoftwareNanjingUniversity43盅讥叉簧桓阎解鲍禾资淆尿居当肮锈橡银呸岳奇骋肤吸叶峪凌听疤搜全粒对象序列化和持久化对象序列化和持久化对象结构的存储与提取需持久化整个对象引用闭包PersistenceclosureJava的serialization规则缺省规则:非static非transient的数据成员用户定义classListimplementsSerializableListnext;privatestaticfinalObjectStreamFieldserialPersistentFields=newObjectStreamField(next,List
42、.class);8/5/2024InstituteofComputerSoftwareNanjingUniversity44怜闲勋琴泡驭渣送委奸矿海刁渊智退讥长春垫驶侩疫偿系退限收隅军废森对象序列化和持久化对象序列化和持久化对象结构的存储与提取闭包可能太大小对象引用(共享的)大对象8/5/2024InstituteofComputerSoftwareNanjingUniversity45允婉榆鞠弊穿猛诽象荤驶兽酪德盈暖晒忧远懂腋来耪橙泅房隔蜜惟侣谩闰对象序列化和持久化对象序列化和持久化对象结构的存储与提取Java的transient修饰子Transientfields不被序列化Staticfi
43、elds也不被序列化开发者负责维护8/5/2024InstituteofComputerSoftwareNanjingUniversity46柄炼氰耪坍郧姨答铃晓状骤细娠响署稍坟瘩秧聚圈拽尉众蚤冠屿邹晾淬霄对象序列化和持久化对象序列化和持久化SchemaevolutionFact:ClasseschangeProblem:ObjectsarestoredofwhichclassdescriptionshavechangedSchema evolution:Atleastoneclassusedbytheretrievingsystemdiffersfromitscounterpartstore
44、dbythestoringsystem.Object retrieval mismatch (Object mismatch):Theretrievingsystemretrievesaparticularobjectwhoseowngeneratingclasswasdifferentinthestoringsystem.Nofullysatisfactorysolution8/5/2024InstituteofComputerSoftwareNanjingUniversity47忙慰灰拓欲擅弱箱每野郁趣誓侨老宿砚气际笔揖庸仔藩藻鸯眼百铃述站放对象序列化和持久化对象序列化和持久化Differ
45、entapproachesNaive,extremeapproaches:ForsakepreviouslystoredobjectsOveramigrationpathfromoldformattonewaone-time,enmasseconversionofoldobjectsnotapplicabletoalargepersistentstoreortoonethatmustbeavailablecontinuouslyMostgeneralsolution:On-the-flyconversionNote:Wecoveronlytheretrievalpart.Whethertowr
46、itebacktheconvertedobjectisaseparateissue.8/5/2024InstituteofComputerSoftwareNanjingUniversity48蝴碰今捆蝗蛔奥爆废泥属械他米苇恼滴注坠桅诫娜忌签嗽趟醒团毒古绢化对象序列化和持久化对象序列化和持久化On-the-flyobjectconversionThreeseparateissues:Detection:CatchobjectmismatchNotification:MakeretrievingsystemawareofobjectmismatchCorrection:Bringmismatche
47、dobjecttoaconsistentstateMakeitacorrectinstanceofthenewclassversion8/5/2024InstituteofComputerSoftwareNanjingUniversity49枣乱荆歹吞津颗痈酒远捆乌乌亦裁诵穆淖爪娃李塘恶拌笼包驭宛纂午妒衙对象序列化和持久化对象序列化和持久化DetectionDetectamismatchbetweentwoversionsofanobjectsgeneratingclassTwocategoriesofdetectionpolicy:Nominalapproach:Eachclassversi
48、onhasaversionnameCentralregistrationmechanismnecessaryStructuralapproach:DeduceclassdescriptorfromactualclassstructureStoreclassdescriptorSimpledetection:compareclassdescriptorsofretrievedobjectwithnewclassdescriptor8/5/2024InstituteofComputerSoftwareNanjingUniversity50勿劲咏航矢凶厩刘全骇句鞘冗拳稽命卓瓶摸蝇啼监喊弥矿顶烽唉瑚康
49、汰搬对象序列化和持久化对象序列化和持久化Detection:StructuralApproachWhatdoestheclassdescriptorneedtocontain?Trade-offbetweenefficiencyandreliabilityTwoextremeapproaches:C1:classnameC2:entireclasstext(e.g.abstractsyntaxtree)Reasonableapproaches:C3:classname,listofattributes(nameandtype)C4:inadditiontoC3:classinvariant8/
50、5/2024InstituteofComputerSoftwareNanjingUniversity51晤取循磊弓据丽匪叮腿阉铣窖仓寝雷腾陨葡凸掠笑滥事旺侧孔医逼死差爸对象序列化和持久化对象序列化和持久化NotificationWhathappenswhenthedetectionmechanismhascaughtanobjectmismatch?LanguagelevelmechanismClassANYcouldincludeaprocedure:correct_mismatchis-Handleobjectretrievalmismatch.localexception:EXCEPTI
51、ONSdocreateexceptionexception.raise(Routinefailure:Objectmismatchduringretrieval)end8/5/2024InstituteofComputerSoftwareNanjingUniversity52剃针卒舆嘉只慑消毅演孺翻挖刊衅份欧桔榴军才决勺式蠕旅茁贮庆蹦炬阴对象序列化和持久化对象序列化和持久化CorrectionHowdowecorrectanobjectthatcausedamismatch?Currentsituation:Retrievalmechanismhascreatedanewobject(dedu
52、cedfromastoredobjectwithsamegeneratingclass)Amismatchhasbeendetectednewobjectisintemporary(maybeinconsistent)state8/5/2024InstituteofComputerSoftwareNanjingUniversity53痪闻堪摹津谴净陌诈弄疹石郝陛悬瓤磐染谢运柑爆翔瓤惑梁疯痔授丹刁访对象序列化和持久化对象序列化和持久化Correction增加attribute删除attribute8/5/2024InstituteofComputerSoftwareNanjingUniversi
53、ty540.0Attributewasnotinstoredversion.FieldisinitializedtodefaultvalueofattributetypeStoredversionhadafield.Newversionhasremovedattribute.Attributeshavenotchanged.汉缩什睫珐犹弦拘毋进爬店冒实扼伎哼已炽诗烹唱倚虱观簧殴痒吊老怒媒对象序列化和持久化对象序列化和持久化Correctioncorrect_mismatchis-Handleobjectretrievalmismatch-bycorrectlysettingupbalance.
54、dobalance:=deposits.total-withdrawals.totalensureconsistent:balance=deposits.total-withdrawals.totalend8/5/2024InstituteofComputerSoftwareNanjingUniversity55depositswithdrawalsbalance0.0900100200240300newfield(initializedtodefaultvalue)oldfieldsWrong!维护不变式维护不变式沃翻蜀昆倍梨梗札靡仔囚稀漾坎急瞧浑郊加屡范拷药双灼座尔挑尾汇露婉对象序列化和持
55、久化对象序列化和持久化自动对象转换:JavaserialVersionUID自动定义(根据类文件生成)1.Classname2.Theclassmodifiers3.Thenameofeachinterface4.Foreachfieldoftheclass(exceptprivatestaticandprivatetransientfields):ThenameofthefieldThemodifiersofthefieldThedescriptorofthefield5.Foreachmethodincludingconstructors,exceptprivatemethodsandco
56、nstructors:ThenameofthemethodThemodifiersofthemethodThedescriptorofthemethod8/5/2024InstituteofComputerSoftwareNanjingUniversity56伞滤僳他藏铰孟电还隔坟箍彩努归渣糜蜀傻缆停罩陕亢痹来膀圣维扛痴碳对象序列化和持久化对象序列化和持久化自动对象转换:Java手工指定ANY-ACCESS-MODIFIERstaticfinallongserialVersionUID=42L;类改变时仍然能够反序列化Java定义了一些“兼容”条件,符合条件的自动转换可以容忍的:addingf
57、ields,etc.太糟糕的:“Changingthetypeofafield”,deletingfields,etc8/5/2024InstituteofComputerSoftwareNanjingUniversity57嗣寅鸭处疡弹蔬啼惫翅姐舟屹承寻翰驾庸檬犁撩警萄揩赁革盲拯栏撤纲羔对象序列化和持久化对象序列化和持久化对于实在“糟糕”的类修改可以定制序列化和反序列化方法privatevoidreadObject(ObjectInputStreamin)privatevoidwriteObject(ObjectOutputStreamout)8/5/2024InstituteofCompu
58、terSoftwareNanjingUniversity58塞癣问官芽裹诫月耕巢秩毯索讯静硼多畦誓烬磊桩宵邵惧备模捅鹤金取罐对象序列化和持久化对象序列化和持久化摘要对象序列化对象持久化LanguagelevelDatabasesHibernate8/5/2024InstituteofComputerSoftwareNanjingUniversity59掀羞巩孙瑟卫琳落坏榆痘浆漳末毕壳苛狡迭看背惹浩吴蹿婆蒂难测恬少檄对象序列化和持久化对象序列化和持久化对象持久化与数据库Deficiencyoflanguagelevelmechanismsthereisonlyoneentryobject;the
59、reisnosupportforcontent-basedqueries;eachcalltoretrieved re-createstheentirestructure,withnosharingofobjectsbetweensuccessivecalls;thereisnosupportforlettingdifferentclientapplicationsaccessthesamepersistentdatasimultaneouslyafull-fledgedsolutionrequirestakingadvantageofdatabasetechnology8/5/2024Ins
60、tituteofComputerSoftwareNanjingUniversity60搪吱抚凭朽曲树以伸稚正魂扬剿河剖老琐吝氓狈铺霸爷寻癸陕锋脖鼓瞳布对象序列化和持久化对象序列化和持久化对象持久化与数据库AsetofmechanismsforstoringandretrievingdataitemsisaDBMSifitsupportsthefollowingitems:PersistenceProgrammablestructureArbitrarysizeAccesscontrolProperty-basedqueryingIntegrityconstraintsAdministratio
61、nSharingLockingTransactions8/5/2024InstituteofComputerSoftwareNanjingUniversity61自然地,要用数据库来存储持久化对象疮瓢国贷槛库李霞植醛煎肖机压阔鉴逗今走泽埠你窒几葵涝命酌窖液答诺对象序列化和持久化对象序列化和持久化对象持久化与数据库关系型数据库:数据库的主流Arelationaldatabaseisasetofrelations,eachcontainingasetoftuples (orrecords).关系代数Selection,Projection,Join8/5/2024InstituteofComput
62、erSoftwareNanjingUniversity62忍女明缓烘堡斧察韶姨涕脸机奈艳蔚探囱直瓮虱荤怔范力梢吱念笨乙漓临对象序列化和持久化对象序列化和持久化对象持久化与数据库Operations:relationalalgebra:selection,projection,joinQueries:standardizedlanguage(SQL)Usually“normalized”:everyfieldisasimplevalue;itcannotbeareference8/5/2024InstituteofComputerSoftwareNanjingUniversity63“TheCa
63、rterhouseofParma”“TheRedandtheBlack”Title“MadameBovary”“EugnieGrandet”date1830183918561833pages341307425346author“Stendahl”“Stendahl”“Flaubert”“Balzac”Relation books:fieldfieldname(=attribute)columntuple(=row)猪荐罢淹衅现冕估霞遍案馆虾密几豺肃檄珊隔赴套基搅逞瞳芜清凄村渤吨对象序列化和持久化对象序列化和持久化OperationsSelection:date 1833ProjectionJo
64、in8/5/2024InstituteofComputerSoftwareNanjingUniversity64“TheCarterhouseofParma”Title“MadameBovary”date18391856pages307425author“Stendahl”“Flaubert”谨禹垣搜帛乞胚金债齐您储偿泣滴孝碍鼓惨咙卸壁翠孵胶削陕裁序恬佩矩对象序列化和持久化对象序列化和持久化OperationsSelectionProjection:on authorJoin8/5/2024InstituteofComputerSoftwareNanjingUniversity65author
65、“Stendahl”“Flaubert”“Balzac”揭仪利锨套趾韵阅疫沈缩据搀瞥凶俩宜回谊寐媚甫筷戮至最诚由洞接蕾痊对象序列化和持久化对象序列化和持久化OperationsSelectionProjectionJoin:booksauthors8/5/2024InstituteofComputerSoftwareNanjingUniversity66“TheCarterhouseofParma”“TheRedandtheBlack”Title“MadameBovary”“EugnieGrandet”date1830183918561833pages341307425346author“St
66、endahl”“Stendahl”“Flaubert”“Balzac”realname“HenriBeyle”“HenriBeyle”“GustaveFlaubert”“HonordeBalzac”birth1783178318211799death1842184218801850name“Stendahl”“Stendahl”“Flaubert”“Balzac”realname“HenriBeyle”“HenriBeyle”“GustaveFlaubert”“HonordeBalzac”birth1783178318211799death1842184218801850Relation au
67、thors:扼捞妇抹坊烤司杭粮固钦懊起赁龙拄为孕魁齿痒遂醋宛芝窗井咆窑悦玉啥对象序列化和持久化对象序列化和持久化UsingrelationaldatabaseswithO-OsoftwareComparisonofterms:Classlibrarytoprovideoperations(correspondingtoembeddedSQL).e.g.JDBC8/5/2024InstituteofComputerSoftwareNanjingUniversity67RelationalrelationtuplefieldnameO-Oclassobjectattribute叫咆跨允底赊掖糊簇饲
68、央能凭衫冲吸惶沦卑脸颠瓣捏娃哮杭兜坑遵报醋救对象序列化和持久化对象序列化和持久化object-relationalinteroperabilityAppropriateusagecases:Youarewritinganobject-orientedsystemwhichmustuseandpossiblyupdateexistingcorporatedata,storedinrelationaldatabases.YourO-Osoftwareneedstostoreobjectstructuressimpleenoughtofitnicelyintherelationalviewofthi
69、ngs.Otherwise,Impedancemismatch!8/5/2024InstituteofComputerSoftwareNanjingUniversity68羞酒娃争敌喊湘脆驱漂峦楔缠拳得痴钾逐睦袁拙缔斩畏下铆钡掷一届膘嘘对象序列化和持久化对象序列化和持久化ImpedanceMismatch关系数据库数据结构规整,成员数目类型固定结构简单,成员类型属于一个既定小集合这些类型由大小固定的类型组合而成那么大小不定的域?表示对象引用的域?基于引用的间接查询?继承?更重要的是:对象identity语义8/5/2024InstituteofComputerSoftwareNanjingUn
70、iversity69龄也魏蹈采董蒋碉赌介淫农绍锥撰潮拿苟咀卵阜迟诧般缎赊拢晕逢飘祸胡对象序列化和持久化对象序列化和持久化Object-orienteddatabasesRemoveimpedancemismatchOvercomeconceptuallimitationsofrelationaldatabases:DatastructuremustberegularandsimpleSmallgroupofpredefinedtypesNormalforms:noreferencestoother“objects”Attempttooffermoreadvanceddatabasefacili
71、ties8/5/2024InstituteofComputerSoftwareNanjingUniversity70烬塞怎仑燥欺银彪然诚檬滔络必翱辜赚骇工细堡哇录裙烷宁需卖韩陌音秦对象序列化和持久化对象序列化和持久化RequirementsforOODBsMinimalrequirements:DatabasefunctionalityEncapsulation:allowhidingtheinternalpropertiesofobjectsandmakethemaccessiblethroughanofficialinterfaceObjectidentity:associatewithe
72、achobjectanidentificationthatisuniqueinthedatabaseReferences:allowanobjecttocontainreferencestootherobjects8/5/2024InstituteofComputerSoftwareNanjingUniversity71群涉墅谱蔑率霜卑甸迅蟹玫誓蝎袍慨炉安审顷根谬护钒陈暴崩厦先臣妒搀对象序列化和持久化对象序列化和持久化RequirementsforOODBsAdditionalrequirements:InheritanceTypingDynamicbindingObjectversionin
73、gSchemaevolutionLongtransactionsLockingObject-orientedqueries8/5/2024InstituteofComputerSoftwareNanjingUniversity72戮籽筹母鼎彬拖咱奋北羌船巨慷暇乳盂琵草掣殃札槛山乃从吏化葛渡粱买对象序列化和持久化对象序列化和持久化OODBsexamplesGemstoneItascaMatisseObjectivityObjectStoreOntosO2PoetMatisseVersantatETHZ:OMSPro8/5/2024InstituteofComputerSoftwareNanjin
74、gUniversity73凉撰柱朴抨巾揩烟蔼土辅君侥未棉姓鸡扭孕秸又棕仆溪颁懒偏拭浴县仿掺对象序列化和持久化对象序列化和持久化摘要对象序列化对象持久化LanguagelevelDatabasesHibernate8/5/2024InstituteofComputerSoftwareNanjingUniversity74族每请叛伟萝冲榴寝疯禾按堪调嚏恳莫呻咨亩肤瞧剩槐气孜都裳位涨授小对象序列化和持久化对象序列化和持久化为什么需要对象持久化框架?OO中轻易实现的对象相同或相等,这样的关系在关系数据库中不存在。OO的一项核心特性是继承,继承很重要,因为它允许创建问题的精确模型,同时可以在层次结构中自
75、上而下的共享属性和行为。而关系数据库不支持继承的概念。对象之间可以轻易的实现一对一,一对多和多对多的关联关系,而关系数据库并不理解这些,它只知道外码指向主码。8/5/2024InstituteofComputerSoftwareNanjingUniversity75哮逮齿耶碟敲亿琶御娟悟镜颅扳墨浦匙儒曰厨拆康坦砂驼匿孩滚砌批缺龋对象序列化和持久化对象序列化和持久化对象持久化框架对象关系映射(ObjectRelationalMapping,简称ORM)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据
76、库中。O/RMapper则指以O/R原理设计的持久化框架(Framework)hibernate,ibatis,jdo,etc.8/5/2024InstituteofComputerSoftwareNanjingUniversity76竣患组纶讶枉铆某民蛀丘鸡姐二彤俭嘎雁致而出绎豢朗览妈皋劣朔只释毅对象序列化和持久化对象序列化和持久化应用分层当前的现实:两层结构三层结构N-层结构8/5/2024InstituteofComputerSoftwareNanjingUniversity77答谁检宫耍俞姿微讳乔试手占板眶悔卑淌杉蒂戳膊捂频蛮左犹敝翻贰舷挽对象序列化和持久化对象序列化和持久化8/5/2
77、024InstituteofComputerSoftwareNanjingUniversity78魏熟尉傀渠伎猛铣碗核恿妥诞合抄汹群列宠怜掐紧躲炽健箕够郧脓售掺运对象序列化和持久化对象序列化和持久化NoORM使用JDBC操作数据库,业务处理逻辑和数据存取逻辑是混杂在一起的。一般基本都是如下几个步骤:1、建立数据库连接,获得Connection对象。2、根据用户的输入组装查询SQL语句。3、根据SQL语句建立Statement对象或者PreparedStatement对象。4、用Connection对象执行SQL语句,获得结果集ResultSet对象。5、然后一条一条读取结果集ResultSet
78、对象中的数据。6、根据读取到的数据,按特定的业务逻辑进行计算。7、根据计算得到的结果再组装更新SQL语句。8、再使用Connection对象执行更新SQL语句,以更新数据库中的数据。9、最后依次关闭各个Statement对象和Connection对象。8/5/2024InstituteofComputerSoftwareNanjingUniversity79封檀被袋姜吁榜朗舱订翼纠荆注愁赤臭颂罪圣咏虱俊类识葡添饶济癣缉友对象序列化和持久化对象序列化和持久化NoORM优点:运行效率高缺点:嵌入大量SQL语句,项目难以维护主要原因:业务处理逻辑和数据存取逻辑完全混杂在一块8/5/2024Insti
79、tuteofComputerSoftwareNanjingUniversity80按蝎尔涟荧吩斗致山抉嘿只豢帝陛晚拉幢芳尼掀荣圈辅牢俊停呵褂酗杨捶对象序列化和持久化对象序列化和持久化Hibernate它是连接Java应用程序和关系数据库的中间件它对JDBCAPI进行了封装,负责Java对象的持久化在分层的软件架构中它位于持久化层,封装了所有数据访问细节,使业务逻辑层可以专注于实现业务逻辑持久化层(PersistenceLayer),即专注于实现数据持久化应用领域的某个特定系统的一个逻辑层面,将数据使用者和数据实体相关联它是一种ORM映射工具,能够建立面向对象的域模型和关系数据模型之间的映射8/
80、5/2024InstituteofComputerSoftwareNanjingUniversity81灸矗撮独相豺桌识触刚烘称忆辙箩饮幻狗粘州鸡功制栗迂完戎踪煎镀研药对象序列化和持久化对象序列化和持久化8/5/2024InstituteofComputerSoftwareNanjingUniversity82歇擒慈祸痴勾模镣激象吱姐抠盏闭享樊柜须翁碱衰疥岛秽错妄垫误寡莽乙对象序列化和持久化对象序列化和持久化8/5/2024InstituteofComputerSoftwareNanjingUniversity83稳奥献恃壕黔考举逻章曼炒跋殆鸥椎职击伍勉柏迫馈舅霓表敌搽诫浇缅帧对象序列化和持久
81、化对象序列化和持久化对象关系映射简单映射将一个类中的一个数据成员定为关键字其它数据成员为属性8/5/2024InstituteofComputerSoftwareNanjingUniversity84搅兜八雁返津类孝递留赴乘聪屈啦讣仍肠旬隶欣慎冻巨拙讹花习轰匆荫箕对象序列化和持久化对象序列化和持久化8/5/2024InstituteofComputerSoftwareNanjingUniversity85packagede.laliluna.example;importjavax.persistence.Entity;importjavax.persistence.Id;importjavax
82、.persistence.GeneratedValue;EntitypublicclassHoneyIdGeneratedValueprivateIntegerid;privateStringname;privateStringtaste;publicHoney()publicIntegergetId()returnid;publicvoidsetId(Integerid)this.id=id;publicStringgetName()returnname;publicvoidsetName(Stringname)this.name=name;publicStringgetTaste()ret
83、urntaste;publicvoidsetTaste(Stringtaste)this.taste=taste;OverridepublicStringtoString()returnHoney:+getId()+Name:+getName()+Taste:+getTaste();Honey.javaHoney.hbm.xml抓候擎服概搀陌祸带专芭坝硒蝎镑伏陛垣障掣蛋甚镑瑟链励页鬃变崔乍旨对象序列化和持久化对象序列化和持久化对象关系映射继承:方案方案1:继承关系中每个具体类对应一个表:继承关系中每个具体类对应一个表子类父类各自映射到各自的关系上特点:在这种映射方式中,每个子类除了映射自己的属
84、性外,还需要映射从父类继承来下的属性;此方式中关系数据模型完全不支持对象的继承关系,不支持多态关联和多态查询8/5/2024InstituteofComputerSoftwareNanjingUniversity86釜洋贡舟义震为棚汇隧母仇示捕咳绩妨琐宠夜龟钞含淫坊痉刊消坐给存股对象序列化和持久化对象序列化和持久化对象关系映射继承方案方案 2:基类(根类)对应一个表:基类(根类)对应一个表所有继承自一个类的类都映射到一个表上增加一栏标记当前记录对应的对象的类特点:这种映射方式支持多态关联和多态查询,并且能获得最佳查询性能,缺点是需要对关系数据模型进行非常规设计,在数据库表中加入额外的区分各个子
85、类的字段,此外,不能为所有子类的属性对应的字段定义notnull约束,无法保证关系数据模型的数据完整性8/5/2024InstituteofComputerSoftwareNanjingUniversity87莉是磊鸵焉清耳窃颅豹波摔棋垣气断泡团率淖棚窥钎悉哭曼坍坷囤意塑嘱对象序列化和持久化对象序列化和持久化对象关系映射继承方案方案 3:每个类对应一个表:每个类对应一个表父类映射的关系与子映射的关系共享相同的主键值,父类关系只记录本身的属性,如果要查询的是子类,则透过外键参考从父类表格中取得继承而來的属性值。特点:这种映射方式支持多态关联和多态查询,而且符合关系数据模型的常规设计规则,缺点是它
86、的查询性能不如第二种映射方式。在这种映射方式下,必须通过表的内连接或左外连接来实现多态查询和多态关联。8/5/2024InstituteofComputerSoftwareNanjingUniversity88花芬复并忍频随滦阵条卤掀浩格秋吁椅氏夜胁撬痉漂缮读晤鸳联魂侯壮灵对象序列化和持久化对象序列化和持久化8/5/2024InstituteofComputerSoftwareNanjingUniversity89沁境阐蛇灿肌性勋侮谈拨阻敝俯座访必述惺静泰蚊褪荤织炒牟萄收断握师对象序列化和持久化对象序列化和持久化8/5/2024InstituteofComputerSoftwareNanjin
87、gUniversity90晋壮喻冀烈劈卉操惶碉轧茵赢垢获喇楞半篓窑议宵慑袱恼附里德抄兼圣爸对象序列化和持久化对象序列化和持久化对象关系映射(继承)1、复杂度:方案1包含重复字段;方案2简单;方案3表较多且之间有外键约束;2、查询性能:方案1若查询父类需查所有子类表;方案2效率高;方案3需要表内连接或左外连接;3、可维护性:方案1若父类属性变化需要修改所有子类对应的表;方案2只需修改一个表;方案3若某个类属性变化只修改这个类对应的表;综上,选择时,可以参考以下原则:1、子类属性不是非常多时,优先考虑方案2,因为其性能最佳。2、子类属性非常多,且对性能要求不是很严格时,优先考虑方案3。8/5/20
88、2491雌曝裙党签篆隔腐源弯涩套七炭苇眷未臃奋练溃汤摇党园型冀拯它柄蓬撂对象序列化和持久化对象序列化和持久化对象关系映射Set映射对象中某属性是一个集合集合元素仅仅是值,无identity映射到另一个关系,用外键表明其属于哪个对象List映射与Set类似再加一栏表示位置8/5/2024InstituteofComputerSoftwareNanjingUniversity92捅俊包谆涡悔琅驼囊镭剪乃货拼俏藤欠青拳氟费天熬苹刮立礼娥塌同狸思对象序列化和持久化对象序列化和持久化对象关系映射Map映射Key-Val属于谁Set和Map可排序8/5/2024InstituteofComputerSof
89、twareNanjingUniversity93锈北膝峙剿离封聋交肢侧峰崇稗捆徘星准荒貌扭它谅庶拈犀凶宫慕长奔缀对象序列化和持久化对象序列化和持久化对象关系映射映射实体关联关系一对一一对多多对一多对多8/5/2024InstituteofComputerSoftwareNanjingUniversity94誉珠坍竖祥洽按诲常盾蝗欠敷淆凰刀才菜矿好搭饯状淳奥眨德巴梨穷踞世对象序列化和持久化对象序列化和持久化作业1.Java语言“transient”关键字与对象序列化有何关系?2.Java语言中实现Serializable接口和Externalizable接口有何不同?3.对象序列化与反序列化时的“Schemaevolution”问题具体指什么?一般如何处理之?4.为何对象持久化要使用数据库?对象模型和关系模型之间有哪些不匹配?何谓对象关系映射?5.尝试学习、使用Hibernate。(此题不需提交)8/5/2024InstituteofComputerSoftwareNanjingUniversity95陕众碉镜坞攀痴果瓮著默斥控陛皇扒二垒盒冻颁郝阎狂能搀湾研汗乖香战对象序列化和持久化对象序列化和持久化