版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
知识点列123掌握ThreadLocal的使用方法4增删改查025注 持久化对象和一级缓存机制 对象的三种状态 一级缓存机制 【案例1】对象的3种状态演示 Hibernate延迟加载机制 基本原理 实现原理 【案例2】延迟加载机制 【案例3】Struts2和Hibernate实现增删改查(2) 【案例4】在项目中使用延迟加载机制 many-to-one关联映射 数据表的关联 many-to-one many-to-one需求下的常见操作 【案例5】many-to-one 持久化对象和一级缓存机制对象的三种状态EmpEmpe=newEmp();一级缓存机制一旦用户对缓存中的数据做了修改,session立刻将数据更新到数据库中。13DROPDROPTABLEIFEXISTSt_foo;CREATETABLEt_foo(t_idint(11)NOT,PRIMARYKEY(t_id))<!DOCTYPEhibernate- DTD" <classname="Foo"<idname="id"type="java.lang.Integer"<propertyname="value"type="java.lang.String"column="t_value" <generatorpackagepackageimportorg.hibernate.Session;importpublicclassHibernateUtilsprivatestaticThreadLocal<Session>tl=newThreadLocal<Session>();privatestaticConfigurationconf;static{factory=}}}**publicstaticSessiongetSession()Sessionsession=tl.get();if(session==null)}return}*publicstaticvoid{Sessionsession=if(session!={);}}packageimportjava.util.Date;packageimportjava.util.Date;importjava.util.List;importorg.hibernate.Query;importorg.hibernate.Session;importorg.junit.Test;}}}importimportpublicclass{{Foofoo=newFoo();Sessionsession=HibernateUtils.getSession();Transactiontx=session.beginTransaction();如上所示,当执行了 session.save(foo);语句执行后,Hibernateinsert mit()操作时,会自劢调用session.flash() 所以,执行了2次update操作新建getfoo1foo2Foofoo2=(Foo)session.get(Foo.class,FooFoofoo2=(Foo)session.get(Foo.class,Foofoo1=(Foo)session.get(Foo.class,一旦用户对缓存中的数据做了修改,session立刻将数据更新到数据库中。(案例结束Hibernate延迟加载机制基本原理调用实现原理该子类重写了getXXX方法,在该方法中触发了对数据库的。loaditeratorHibernateGBLIBSpring——具体使用ThreadLocal——其实是一个线程为KEY的Map,2】延迟加载机制而当调用Foofoo=Foofoo=(Foo)session.load(Foo.class,Foo{publicStringgetValue(){return}}Java.class我们并没有创建Foo$$EnhancerByCGLIB$$b3a0560c这个类,cglib-2.1.3.jar调用了如下所示,Foo$$EnhancerByCGLIB$$b3a0560ccglibFoofinal package增加packageimportimportimportimportorg.hibernate.Query;importorg.junit.Test;importimportpublicclass{publicvoidtestIterator()Sessionsession=HibernateUtils.getSession();Queryquery=session.createQuery("fromFoo");//List<Foo>fooList=Iterator<Foo>fooIt=//selectt_idfromwhile{Foofoo=//select*fromt_foowheret_id=?}}}先执行selectt_idfromt_foo;语句,从数据库中仅仅将id取出;(案例结束参考请新增****@parampublicvoiddelete(Integer[]{Sessionsession=Transactiontx=for(Integerid:projects)Projectproject=newProject();}}packagepackageimportpublicclassProjectDeleteActionextendsBaseActionprivateProjectDaoprojectDao=new//privateInteger[]//OutputpublicStringexecute()throws{return}}}publicInteger[]getProjects()return}publicvoidsetProjects(Integer[]projects)jects=}<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.1//EN" <actionname="list"<result<action<result<actionname="create"<result<action<%@tagliburi="/struts-tags"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN" <linkhref="../css/style.css"type="text/css"rel="stylesheet"<script<body<divcellPadding="0"width="100%"<br<tableclass="tableborder"cellSpacing="0"cellPadding="0"width="100%"border="0"><tr<td <td<td<td<td<s:iterator
<td<inputtype="checkbox"<tdclass="altbg2"href="load.action?project.id=${id}"><b><s:propertyvalue="no"/></b></a><td<b><s:propertyvalue="name"/><td<b><s:propertyvalue="startDate"/><td<b><s:propertyvalue="endDate"/><br测试(略findById**@parampublicProjectfindById(Integer{Sessionsession=Projectproject=(Project)session.get(Project.class,id);return}ject.po.Project;publicclassProjectLoadActionextends{privateProjectDaoprojectDao=new////privateProjectpublicStringexecute()throwsExceptionreturn"success";}{return}{ject=}}project.struts.xml增加<actionname="load"><<actionname="load"<result<linkhref="css/style.css"type="text/css"rel="stylesheet"<body<div<tableclass="guide"cellSpacing="0"cellPadding="0"width="100%"<br<formid=""action=""value=""/><tableclass="tableborder"cellSpacing="0"<tr<tdclass="altbg1"<tdclass="altbg2"valign="middle"<inputtype="text"name="no"<spanstyle="color:red"><tdclass="altbg1"<td<inputtype="text"name="name"<spanstyle="color:red"><tdclass="altbg1"<td<inputtype="text"name="startDate"<spanstyle="color:<tdclass="altbg1"<td<inputtype="text"name="endDate"<spanstyle="color:<br<inputclass="buttontype="button"value="取消"name="settingsubmit"/><inputclass="buttontype="button"value="恢复"name="settingsubmit"/><inputclass="button"type="submit"value=name="settingsubmit"/><tableclass="tableborder"cellSpacing="0"cellPadding="0"width="100%"border="0"><tr<td <td<td<td<td<s:iterator
<td<inputtype="checkbox"<tdclass="altbg2"<a<b><s:propertyvalue="no"/><td<b><s:propertyvalue="name"/><<td<b><s:propertyvalue="startDate"/><td<b><s:propertyvalue="endDate"/><br测跳转到数据更新页新增****@parampublicvoidupdate(Project{Sessionsession=openSession();}ject.po.Project;publicpublicclassProjectUpdateActionextends{privateProjectDaoprojectDao=new//privateProject//OutputpublicStringexecute()throws{return}{return}{ject=}}<actionname<actionname="update"<%@tagliburi="/struts-tags"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN" <linkhref="../css/style.css"type="text/css"rel="stylesheet"<body<divcellPadding="0"width="100%"<br<s:formid="settings"action="update"method="post"<s:hidden<tableclass="tableborder"cellSpacing="0"cellPadding="0"width="100%"border="0"><tr<tdclass="altbg1"<tdclass="altbg2"valign="middle"<s:textfieldname="project.no"<spanstyle="color:red"><tdclass="altbg1"<td<spanstyle="color:red"><tdclass="altbg1"<td<s:textfield<spanstyle="color:<tdclass="altbg1"<td<s:textfield<spanstyle="color:<brname="settingsubmit"/>name="settingsubmit"/><inputclass="button"type="submitvalue=name="settingsubmit"/>测试(略(案例结束4】在项目中使用延迟加载机制请Struts+Hibernate的jar 修改如果在ProjectDao中调用session.close()关闭了session,如果ProjectDao中丌调用session.close方法,这样就造成一个如何在项目中使用延缓加载?OpesoIewpackagepackagepublicclassTestThreadLocalpublicstaticvoidmain(String[]{Somes1=SomeFactory.getSome();}publicstaticvoid{Somes2=SomeFactory.getSome();}}classSome{classSomeFactorypublicstaticSomegetSome()returnnew}}f(s2mian(s1首先注意一点,f()方法和main()方法同样都是在一个线程中,有相同的线程号。的Some对象是同一个。packagepackageimportimportpublicclassTestThreadLocalpublicstaticvoidmain(String[]{Somes1=SomeFactory.getSome();}publicstaticvoid{Somes2=SomeFactory.getSome();}}classSome{classSomeFactoryprivatestaticMap<Long,Some>map=newHashMap<Long,publicstaticSomegetSome()Somesome=if(some==some=new}}}}return假设Some就是Session,如果使用这种机制获取Session,当同一个用户浏览器丌论怎么调用session都是同一个(叧要在相同的线程中)。packagepackagepublicclassTestThreadLocalpublicstaticvoidmain(String[]{Somes1=SomeFactory.getSome();}publicstaticvoid{Somes2=Somes2=SomeFactory.getSome();}}classSome{classSomeFactory//privatestaticMap<Long,Some>map=newHashMap<Long,privatestaticThreadLocal<Some>tl=newpublicstaticSomegetSome()//longthreadId=//Somesome=map.get(threadId);Somesome=tl.get();if(some==null)some=new//map.put(threadId,}return}}测试(略1(推荐packageimportpackageimportimportimportimportpublicclassHibUtilprivatestaticConfigurationprivatestaticSessionFactoryconf=new}publicstaticSessionreturn}}packagepackageimportorg.hibernate.Session;importpublicclassHibernateUtilsprivatestaticThreadLocal<Session>tl=newThreadLocal<Session>();privatestaticConfigurationconf;privatestaticSessionFactorystaticfactory=}publicstaticSessiongetSession()}}Sessionsession=tl.get();if(session==null)}return}publicstaticvoid{Sessionsession=tl.get();if(session!=null){);}}在器中调用closeSession()关闭Session。"-//Hibernate/HibernateConfigurationDTD3.0//EN"<propertyname="connection.url"><property<property<!--<property<property <propertypackagepackageimportimportimportpublicclassHibernateUtilsprivatestaticConfigurationprivatestaticSessionFactorystaticconf=newfactory=}**}}publicstaticSessiongetSession()return}*publicstaticvoidcloseSession()Sessionsession=if(session!={}}(案例结束many-to-one关联映射数据表的关联数据表的关联丌一定导致Hibernate关联映射。t_dept(t_id)的时候步骤1privateDept}<many-to-onename="dept"class="Dept"many-to-one需求下的常见操作1)保存2)取出Emp(带着Dept)Empemp=<many-to-one...Dept还是用单独的SQLfetchjoinSQL3)查询Emp(带着Dept)HQL:fromDept还是用单独的HQLfromEmpeleftouterjoinfetche.dept4)根据特定条件查询Emp(带着Dept)HQL:fromEmpewhereHQLfromE='...'5)根据Dept的属性查询Emp(带着Dept)HQL:fromEmpewhereHQL:fromEmpeleftouterjoinfetche.deptwheret_emp注意:这里丌用写主外键关联约束也是可以的(现在约束的使用越来越少PRIMARYKEYt_loct_locvarchar(200)NOTPRIMARYKEY)insertintot_dept(t_name,t_loc))DROPTABLEIFEXISTSCREATETABLEt_deptDROPTABLEIFEXISTSCREATETABLEt_empt_idint(11)NOTNULLt_namevarchar(50)NOTNULL,t_salarydouble(9,2)NOTNULL,t_hire_datedateNOTNULL,t_registerchar(1)NOTt_idint(11)NOTNULLt_dept_idint(11)NOTEmpDeptEmp EmpsDeptDept DeptEmpsItem OrderItem packagepackageimportpublicclass{privateIntegerid;privateStringname;privatedoublesalary;privateDatehireDate;privateDatelastLogin;publicIntegergetDeptId(){returnpublicvoidsetDeptId(IntegerdeptId)this.deptId=publicIntegergetId(){returnpublicvoidsetId(Integerid){this.id=publicStringgetName(){returnpublicvoidsetName(Stringname){=publicdoublegetSalary(){returnpublicvoidsetSalary(doublesalary){this.salary=publicDategetHireDate(){returnpublicvoidsetHireDate(DatehireDate)this.hireDate=publicDategetLastLogin(){returnpublicvoidsetLastLogin(DatelastLogin)this.lastLogin=publicbooleanisRegister(){returnpublicvoidsetRegister(booleanregister)this.register=}privateInteger<!DOCTYPEhibernate- DTD" <classname="Emp"<idname="id"type="integer"<generator<propertyname="name"type="string"column="t_name"<propertyname="salary"type="double"column="t_salary"<propertyname="hireDate"type="date"column="t_hire_date" packagepackagepublicclass{privateIntegerid;privateStringname;publicIntegergetId(){returnpublicvoidsetId(Integerid){this.id=publicStringgetName(){returnpublicvoidsetName(Stringname){=publicStringgetLocation(){returnpublicvoidsetLocation(Stringlocation)}}}this.location=<!DOCTYPEhibernate- DTD" <classname="Dept"<idname="id"type="integer"<generator<propertyname="name"type="string"column="t_name"<propertyname="location"type="string"column="t_loc" many-to-onemany-to-onepackageimportpublicclass{privateIntegerid;privateStringname;privatedoublesalary;privateDatehireDate;privateDatelastLogin;privateDeptprivateDeptpublicpublicvoidsetDept(Deptdept){this.dept=publicDeptgetDept(){returnpublicIntegergetId(){returnpublicvoidsetId(Integerid){this.id=publicStringgetName(){returnpublicvoidsetName(Stringname){=publicdoublegetSalary(){returnpublicvoidsetSalary(doublesalary){this.salary=publicDategetHireDate(){returnpublicvoidsetHireDate(DatehireDate)this.hireDate=publicDategetLastLogin(){returnpublicvoidsetLastLogin(DatelastLogin)this.lastLogin=publicbooleanisRegister(){returnpublicvoidsetRegister(booleanregister)this.register=}<!DOCTYPEhibernate- "
DTD <classname="Emp"<idname="id"type="integer"<generator<propertyname="name"type="string"column="t_name"<propertyname="salary"type="double"column="t_salary"<propertyname="hireDate"type="date"column="t_hire_date"<many-to-onename="dept"class="Dept"<many-to-onename="dept"class="Dept"column="t_dept_id" 提供的<方方配置文件"-//Hibernate/HibernateConfigurationDTD <propertyname="connection.url"><property<propertyHibernate<!--<property<property<property insertinsertintot_dept(t_name,t_loc)packagepackagepublicclass{publicvoidtestSaveEmp()Empemp=newEmp();emp.setHireDate(newDate());Deptdept=newDept();Sessionsession=HibernateUtils.getSession();Transactiontx=session.beginTransaction();}}packagepackageimportimportimportimportpublicclass{publicvoidtestGetEmp()Sessionsession=HibernateUtils.getSession();Empemp=(Emp)session.get(Emp.class,1);}}}Hibernate:selectdept0_.t_idast1_1_0_,dept0_.t_nameasHibernate:selectdept0_.t_idast1_1_0_,dept0_.t_nameast2_1_0_,dept0_.t_locast3_1_0_fromt_deptdept0_wheredept0_.t_id=?Hibernate:selectemp0_.t_idast1_0_0_,emp0_.t_nameast2_0_0_,emp0_.t_salaryast3_0_0_,emp0_.t_hire_dateast4_0_0_,emp0_.t_last_loginast5_0_0_,emp0_.t_registerast6_0_0_,emp0_.t_dept_idast7_0_0_fromt_empemp0_,fromt_empejoint_dept即使我们使用的是get方法获取的Emp对象EmpEmpemp=(Emp)session.get(Emp.class,<many-to-onename="dept"class="Dept"让我们把两条SQL合并为一条<many-to-onename="dept"class="Dept"lazy="false"<<many-to-onename="dept"class="Dept"戒<many-to-onename="dept"class="Dept"lazy="proxy"<many-to-onename="dept"class="Dept"lazy="false"Hibernate:Hibernate:selectemp0_.t_idast1_0_1_,emp0_.t_nameast2_0_1_,emp0_.t_salaryast3_0_1_,emp0_
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 饭店顾客停车场地租赁合同
- 燃气管道改造维护保养施工合同
- 2025年度融资担保业务风险评估合同范本2篇
- 交通枢纽绿化区道路施工合同
- 电子商务专家聘任合同
- 摄影工作室摄影师聘用合同
- 二零二五年房产租赁押金返还与住房按揭贷款合同3篇
- 城市地下铁道供水井施工合同
- 交通运输行业医师聘用合同
- 体育器材租赁合同解除
- 物权转移协议
- 高三高考地理一轮课时练习:洋流(单选题)
- 2024年餐饮类“食品安全及质量管理员”知识考试题库(附含答案)
- 三年级上册寒假每日一练
- (正式版)SHT 3115-2024 石油化工管式炉轻质浇注料衬里工程技术规范
- 超声引导下心包穿刺置管术
- 无人机驾驶员航空知识手册培训教材(多旋翼)
- 员工年度工作计划范文
- 古诗文系列课件模板-清平调·其一
- 桩身完整性考试试题及完整答案(包括低应变、钻芯、声波透射法)
- 类文阅读:一起长大的玩具(金波)
评论
0/150
提交评论