2013達內java課件代碼練習hibernate exday_第1頁
2013達內java課件代碼練習hibernate exday_第2頁
2013達內java課件代碼練習hibernate exday_第3頁
2013達內java課件代碼練習hibernate exday_第4頁
2013達內java課件代碼練習hibernate exday_第5頁
已閱讀5頁,還剩57頁未讀, 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

練習列1234注 1:Hibernate3DROPTABLEIFEXISTSDROPTABLEIFEXISTSt_foo;CREATETABLEt_foo(t_idint(11)NOTNULLt_valuevarchar(50)NOTNULL,PRIMARYKEY(t_id)) DTD" <classname="Foo"<generator packagepackageimportorg.hibernate.Session;importpublicclassHibernateUtilsprivatestaticThreadLocal<Session>tl=newThreadLocal<Session>();privatestaticConfigurationconf;privatestaticSessionFactoryfactory;static{conf=newConfiguration();factory=}**publicstaticSessiongetSession()//factory.getCurrentSession();Sessionsession=tl.get();if(session==null)session=factory.openSession();}return}*publicstaticvoidcloseSession()}}Sessionsession=tl.get();if(session!=null){);}packageimportjava.util.Date;importjava.util.I importjava.util.List;importpackageimportjava.util.Date;importjava.util.I importjava.util.List;importorg.hibernate.Query;importorg.hibernate.Session;importorg.junit.Test;importimport{{Foofoo=newFoo();//1在的foo是暫時態(tài)Transactiontx=session.beginTransaction();//2在的foo是持久態(tài)}}}session.save(foo);語句執(zhí)行后,Hibernateinsert作又操作。印 mit()操作時,會自勱調用session.flash() 所以,執(zhí)行了2次update操作新建被處過方Foofoo2=(Foo)session.get(Foo.class,Foofoo1=(Foo)session.get(Foo.class,Foofoo2=(Foo)session.get(Foo.class,Foofoo1=(Foo)session.get(Foo.class,一旦用戶對緩存中的數據做了修改,session刻將數據更新到數據庫中。中丌會把游2:延遲加載機制用用為如何FooFoofoo=(Foo)session.load(Foo.class,了()Foo$$EnhancerByCGLIB$$b3a0560cFoo$$EnhancerByCGLIB$$b3a0560cextendFoo{publicStringgetValue(){return}}Java迚制.class我們并沒有創(chuàng)建Foo$$EnhancerByCGLIB$$b3a0560c這個類,完成調用了實這由Foofinal 的,package增加 packageimportimport importimportorg.hibernate.Query;importorg.junit.Test;importimport{publicvoid tor()Sessionsession=HibernateUtils.getSession();Queryquery=session.createQuery("fromFoo");//List<Foo>fooList= tor<Foo>fooIt= //selectt_idfromwhile{Foofoo=//select*fromt_foowheret_id=?}}}打印4條查詢語句,表明當query.i 先執(zhí)行selectt_idfromt_foo;語句,從數據庫中僅僅將id取出;請**@param**@param{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<resultname="success"type="redirectAction"><actionname="delete"<<resultname="success"type="redirectAction"><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN" <script<body<divcellPadding="0"width="100%"<br<tableclass="tableborder"cellSpacing="0"cellPadding="0"width="100%"border="0"><tr<td<td<b>編號<td<b>名稱<td<b>開始時間<td<b>結束時間 tor

<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""""刪除項目""""**@parampublicProjectfindById(Integer{Sessionsession=Projectproject=(Project)session.get(Project.class,id);return}ject.po.Project;publicclassProjectLoadActionextends{privateProjectDaoprojectDao=new////privateProjectpublicStringexecute()throwsExceptionproject=projectDao.findById(project.getId());return"success";}{return}{ject=}}project.struts.xml增加<actionname="load"><<actionname="load"<result<body<div<tableclass="guide"cellSpacing="0"cellPadding="0"width="100%"<br<formid=""action=""value=""/>width="100%"<tr<td<tdclass="altbg1"<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="buttonvalue="取消"name="settingsubmit"/><inputclass="buttontype="buttonvalue="恢復"name="settingsubmit"/><inputclass="buttontype="submitvalue"name="settingsubmit"/><tableclass="tableborder"cellSpacing="0"cellPadding="0"width="100%"border="0"><tr<td<td<b>編號<td<b>名稱<td<b>開始時間<td<b>結束時間 tor

<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""""刪除項目""""**@param**@parampublicvoidupdate(Project{Sessionsession=openSession();Transactiontx=session.beginTransaction();}ject.po.Project;publicpublicclassProjectUpdateActionextends{privateProjectDaoprojectDao=new//privateProject//OutputpublicStringexecute()throws{return}{return}{ject=}}<actionname="update"<actionname="update"<resultname="success"type="redirectAction"><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN" <body<divcellPadding="0"width="100%"<br<s:hidden<tableclass="tableborder"cellSpacing="0"cellPadding="0"width="100%"border="0"><tr<td<tdclass="altbg1"<spanstyle="color:red"><tdclass="altbg1"<td<spanstyle="color:red"><tdclass="altbg1"<td<s:textfield<spanstyle="color:<tdclass="altbg1"<td<s:textfield<spanstyle="color:<br<inputclass="buttontype="buttonvalue="取消"name="settingsubmit"/><inputclass="buttontype="buttonvalue="恢復"name="settingsubmit"/><inputclass="buttontype="submitvalue=name="settingsubmit"/>4請Struts+Hibernate的jarfindById法,將getload()方 如果在ProjectDao中調用session.close()關閉了session,如果ProjectDao中丌調用session.close方法,那么中取這樣就造成一個必在中調用閉OeesVew候才在sessionsession(要一直持有類packagepackagepublicclassTestThreadLocalpublicstaticvoidmain(String[]}publicstaticvoid{}}classSome{classSomeFactorypublicstaticSomegetSome()returnnew}}首先注意一點,f()方法和main()方法同樣都是在一個線程中,有相同的線程號。以當先線Id為key,創(chuàng)建了一Some象,在同一個線程中,利用SomeFactory到的Some對象是同一個。packagepackageimportimportpublicclassTestThreadLocalpublicstaticvoidmain(String[]}publicstaticvoid{}}classSome{classSomeFactorypublicstaticSomegetSome()Somesome=map.get(threadId);if(some==some=newmap.put(threadId,}}}}return假設Some就是Session,如果使用這種機制獲取Session,當同一個用戶瀏覽器丌論怎么調用session是同一個(叧要在相同的線程中)。packagepackagepublicclassTestThreadLocalpublicstaticvoidmain(String[]}publicstaticvoid{}}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}}packageimportopenSession調packageimportimportimportimportpublicclassHibUtilprivatestaticConfigurationprivatestaticSessionFactoryconf=newfactory=}publicstaticSessionreturn}}packagepackageimportorg.hibernate.Session;importpublicclassHibernateUtilsprivatestaticThreadLocal<Session>tl=newThreadLocal<Session>();privatestaticConfigurationconf;privatestaticSessionFactorystaticconf=newConfiguration();factory=}publicstaticSessiongetSession()}}Sessionsession=tl.get();if(session==null)session=factory.openSession();}return}publicstaticvoid{Sessionsession=tl.get();if(session!=null){);}}在器中調用closeSession()關閉Session。"-//Hibernate/Hibernate"-//Hibernate/HibernateConfigurationDTD3.0//EN"<propertyname="connection.url"><property<property<<propertyname="connection.driver_class"><property<property <propertypackagepackageimportimportimportpublicclassHibernateUtilsprivatestaticConfigurationprivatestaticSessionFactorystaticconf=newfactory=}**}}publicstaticSessiongetSession()return}*publicstaticvoidcloseSession()Sessionsession=if(session!={}}新建t_empDROPTABLEIFDROPTABLEIFEXISTSt_emp;CREATETABLEt_emp(t_idint(11)NOTNULLt_namevarchar(50)NOTNULL,t_salarydouble(9,2)NOTNULL,t_hire_datedateNOTNULL,t_last_logintimestampNOTNULL,t_registerchar(1)NOTNULL,t_dept_idint(11)NOTNULL,PRIMARYKEY(t_id))DROPDROPTABLEIFEXISTSCREATETABLEt_deptt_idint(11)NOTNULLt_namevarchar(50)NOTNULL,t_locvarchar(200)NOTNULL,PRIMARYKEY(t_id))insertintot_dept(t_name,t_loc)當我們寫員工表Emp和部門表DeptEmp 求可以叨做此時員工Emps不部門DeptDept 以叨做此時部門DeptEmps再比如當我們寫購物車訂單Order和訂單項ItemItem 當看一個條目Item時,我們也要看該條目屬亍哪個訂單OrderOrderItem packagepackageimportpublicclassEmpprivateIntegerprivateStringname;privatedoublesalary;privateDatehireDate;privateDatelastLogin;privatebooleanregister;privateIntegerdeptId;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=} DTD" <classname="Emp"<idname="id"type="integer"<generator packagepackagepublicclass{privateIntegerid;privateStringname;privateStringlocation;publicIntegergetId(){returnpublicvoidsetId(Integerid){this.id=publicStringgetName(){returnpublicvoidsetName(Stringname){=publicStringgetLocation(){returnpublicvoidsetLocation(Stringlocation)this.location=}} DTD" <classname="Dept"<idname="id"type="integer"<generator 每一次我們取出一個員工,同時查看他的信息時,還需要通過deptId找到指定的Dept再次注意:并丌是有表關聯時many-to-one射,是當有如上所示many-to-onepackageimportpublicclass{privateIntegerid;privateStringname;privatedoublesalary;privateDatehireDate;privateDatepackageimportpublicclass{privateIntegerid;privateStringname;privatedoublesalary;privateDatehireDate;privateDatelastLogin;privatebooleanregister;//privateIntegerprivateDeptpublicDeptgetDept(){returnpublicvoidsetDept(Deptdept){this.dept=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=} DTD" <classname="Emp"<idname="id"type="integer"<generator 提方方"-//Hibernate/HibernateConfigurationDTD3.0//EN"<propertyname="connection.url"><property<property<property<property<propertyinsertintot_dept(t_name,t_loc)insertintot_dept(t_name,t_loc)packagepackage{publicvoidtestSaveEmp()Empemp=newEmp();emp.setHireDate(newDate());}}}Transactiontx=session.beginTransaction();Deptdept=newDept();packagepackageimportimportimportimport{publicvoidtestGetEmp()Empemp=(Emp)session.get(Emp.class,1);}}Hibernate:selectdept0_.t_idast1_1_0_,dept0_.t_nameast2_1_0_,dept0_.t_locast3_1_0_fromt_deptdept0_wheredept0_.t_id=?Hibernate:selectHibernate: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請注意打印出來的Emp是本類,而Dept確實類即使我們使用的是get方法獲取的Emp對象EmpEmpemp=(Emp)session.get(Emp.class,用到了Dept對象時,才勱態(tài)加載了Dept的對象。讓我們把兩條SQL合并為一條lazy="false" "lazy="false"Hibernate:Hibernate:selectemp0_.t_idast1_0_1_,emp0_.t_nameast2_0_1_,emp0_.t_salaryast3_0_1_,emp0_.t_hire_dateast4_0_1_,emp0_.t_last_loginast5_0_1_,emp0_.t_registerast6_0_1_,emp0_.t_dept_idast7_0_1

溫馨提示

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

評論

0/150

提交評論