使用HibernateTemplate
HibernateTemplate 可將Hibernate 的持久層訪問模板化,使用HibernateTemplate 非常簡單。創(chuàng)建Hi bernateTemplate 實(shí)例后,注入一個(gè)SessionFactory 的引用,就可執(zhí)行持久化操作。SessionFactoyr 對象可通過構(gòu)造參數(shù)傳入,或通過設(shè)值方式傳入。例如:
//獲取Spring 上下文
ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");
//通過上下文獲得SessionFactory
SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory") ,
HibernateTemplate 提供如下三個(gè)構(gòu)造函數(shù):
? HibernateTemplateO 。
? HibernateTemplate(org.hibernate.SessionFactory sessionFactory)。
? HibernateTemplate(org.hibernate.SessionFactory sessionFactory, boolean allowCreate) 。?
第一個(gè)構(gòu)造函數(shù):構(gòu)造一個(gè)默認(rèn)的HibernateTemplate 實(shí)例,因此,使用HibernateTemplate實(shí)例之前,還必須使用方法setSessionFactory(SessionFactory sessionFactory)來為HibernateTemplate 傳入SessionFactory 的引用。
第二個(gè)構(gòu)造函數(shù):在構(gòu)造時(shí)已經(jīng)傳入SessionFactory 引用。
第三個(gè)構(gòu)造函數(shù):其boolean 型參數(shù)表明,如果當(dāng)前線程己經(jīng)存在一個(gè)非事務(wù)性的Session ,是否直接返回此非事務(wù)性的Session 。
對于在Web 應(yīng)用中,通常啟動(dòng)時(shí)自動(dòng)加載ApplicationContext , SessionFactory 和DAD對象都處在Spring 上下文管理下。因此無須在代碼中顯式設(shè)置,可采用依賴注入解耦SessionFactory 和DAO.
?其依賴關(guān)系可通過配置文件來設(shè)置












































?
在DAO 實(shí)現(xiàn)類中,可采用更簡單的方式來取得HibemateTemplate的實(shí)例。代碼如下:






























































































更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
