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












































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






























































































更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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