Spring之HibernateTemplate 和HibernateDaoSupport

spring提供訪問數據庫的有三種方式:

?

HibernateDaoSupport

HibernateTemplate(推薦使用)

jdbcTemplate(我們一般不用)

?

類所在包:

HibernateTemplate:org.springframework.orm.hibernate3.HibernateTemplate

HibernateDaoSupport:org.springframework.orm.hibernate3.support.HibernateDaoSupport

?

? ? ? ?spring如果想整合hibernate的話,首先就應該獲得SessionFactory這個類,然后再通過獲得session就可以進行訪問數據庫了,即spring提供的類HibernateDaoSupport,HibernateTemplate應該是有setSessionFactory,在使用的時候注入一下就可以了。HibernateTemplate類中的方法是spring封裝了hibernate中的方法,在使用完了以后會自動釋放session。而如果使用了HibernateDaoSupport的getSession方法,就需要配套的用releaseSession(Session?session)或者session.close來關閉session,無法實現自動管理session。所以很多人都傾向于用spring的?Hibernatetemplate類或者HibernateDaoSupport的getHibernateTemplate方法來實現實現數據庫的交互,當然,如果遇到hibernatetemplate無法實現的功能,可以使用?HibernateDaoSupport。

?

首先我們先來看一下HibernateTemplate類:

首先我們來說一下我們為什么要用HibernateTemplate,其實這個類就是我們平常使用hibernate進行dao操作的一個模版,我們不需要那些開頭的開啟事務、獲得session,結尾的提交事務,關閉session等操作了,這些工作是HibernateTemplate都給我們封裝好了,我們直接調用其dao的操作方法就可以了,并且他還給我們封裝了hibernate的幾乎所有的異常,這樣我們在處理異常的時候就不要記住那么多繁瑣的異常了。所以我們就叫他是一個hibernate中dao操作的模版,他提供的常用方法:


get?從數據庫相關表中獲取一條記錄并封裝返回一個對象(Object)?
load?作用與get基本相同,不過只有在對該對象的數據實際調用時,才會去查詢數據庫?
save?添加記錄?
saveOrUpdate?判斷相應記錄是否已存在,據此進行添加或修改記錄
update?修改記錄?
delete?刪除記錄??

?

下面我們來看一下HibernateTemplate的源碼來看一下他的具體方法是怎么樣實現的,其實你觀察源碼可以發現,他所提供的方法幾乎都是一個實現實現的。下面我們就以save方法來具體看一下:

?

?

[java]?view plaincopyprint?
  1. public?Serializable?save(final?Object?entity)?throws?DataAccessException?{??
  2. return?(Serializable)?executeWithNativeSession(new?HibernateCallback()?{??
  3. public?Object?doInHibernate(Session?session)?throws?HibernateException?{??
  4. checkWriteOperationAllowed(session);??
  5. return?session.save(entity);??
  6. }??
  7. });}??



?

? ? ? ?我們從源碼中可以發現,HibernateTemplate把我們hibernate的異常都封裝成了一個DataAccessException?。好了,解釋一下上面的代碼,上面代碼中主要是調用了executeWithNativeSession這個方法,其實這個方法就是給我們封裝好的hibernate開頭和結尾一些列操作,他需要一個參數,這個參數是一個回調的對象,其實這個對象是實現了一個HibernateCallback的接口,實現這個接口需要實現這個接口里面的方法doInHibernate,這個方法需要把當前的session傳遞過來,其實他就是把他原先模版里獲得的session傳過去。然后在在doInHibernate中利用模版中得到的session進行保存數據。其實我們調用save的過程就是給他傳一個回調對象的過程,我們可以看到,他的回調對象是new出來的。

?

?????如果你還沒看懂的話,那大家來看一下下面我們實現自己的HibernateTemplate,他的思路和spring提供的基本是一樣的:其中MyHibernateCallback?是一個簡單接口:

?

[java]?view plaincopyprint?
  1. import?org.hibernate.Session;??
  2. public?class?MyHibernateTemplate?{??
  3. public?void?executeWithNativeSession(MyHibernateCallback?callback)?{??
  4. Session?s?=?null;??
  5. try?{??
  6. s?=?getSession();??
  7. s.beginTransaction();??
  8. callback.doInHibernate(s);??
  9. s.getTransaction().commit();??
  10. }?catch?(Exception?e)?{??
  11. s.getTransaction().rollback();??
  12. }?finally?{??
  13. //...??
  14. }??
  15. }??
  16. private?Session?getSession()?{??
  17. //?TODO?Auto-generated?method?stub??
  18. return?null;??
  19. }??
  20. public?void?save(final?Object?o)?{??
  21. new?MyHibernateTemplate().executeWithNativeSession(new?MyHibernateCallback()?{??
  22. public?void?doInHibernate(Session?s)?{??
  23. s.save(o);??
  24. }??
  25. });??
  26. }??
  27. }??



?

?

? ? 好了,原理我們介紹完了之后,下面我們來看一下具體應用,這個HibernateTemplate在我們的程序中怎么用,在上面我們也說過了,這個用法主要是把sessionfactory注入給我們的HibernateTemplate

首先我們來看一下beans.xml的配置:

?

?

[html]?view plaincopyprint?
  1. <?xml?version="1.0"?encoding="UTF-8"?>??
  2. <beans?xmlns="http://www.springframework.org/schema/beans"??
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??
  4. xmlns:context="http://www.springframework.org/schema/context"??
  5. xmlns:aop="http://www.springframework.org/schema/aop"??
  6. xmlns:tx="http://www.springframework.org/schema/tx"??
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans??
  8. ???????????http://www.springframework.org/schema/beans/spring-beans-2.5.xsd??
  9. ???????????http://www.springframework.org/schema/context??
  10. ???????????http://www.springframework.org/schema/context/spring-context-2.5.xsd??
  11. ???????????http://www.springframework.org/schema/aop??
  12. ???????????http://www.springframework.org/schema/aop/spring-aop-2.5.xsd??
  13. ???????????http://www.springframework.org/schema/tx???
  14. ???????????http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">??
  15. <bean?id="dataSource"??
  16. class="org.apache.commons.dbcp.BasicDataSource"??
  17. destroy-method="close">??
  18. <property?name="driverClassName"?value="com.mysql.jdbc.Driver"?/>??
  19. <property?name="url"?value="jdbc:mysql://localhost:3306/spring"?/>??
  20. <property?name="username"?value="root"?/>??
  21. <property?name="password"?value="bjsxt"?/>??
  22. </bean>??
  23. <bean?id="sessionFactory"??
  24. class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">??
  25. <property?name="dataSource"?ref="dataSource"?/>??
  26. <property?name="annotatedClasses">??
  27. <list>??
  28. <value>com.bjsxt.model.User</value>??
  29. <value>com.bjsxt.model.Log</value>??
  30. </list>??
  31. </property>??
  32. <property?name="hibernateProperties">??
  33. <props>??
  34. <prop?key="hibernate.dialect">??
  35. org.hibernate.dialect.MySQLDialect??
  36. </prop>??
  37. <prop?key="hibernate.show_sql">true</prop>??
  38. </props>??
  39. </property>??
  40. </bean>??
  41. <bean?id="hibernateTemplate"?class="org.springframework.orm.hibernate3.HibernateTemplate">??
  42. <property?name="sessionFactory"?ref="sessionFactory"></property>??
  43. </bean>??
  44. <bean?id="UserDao"?class="com.bzu.dao.userDao">??
  45. <property?name="hibernateTemplate"?ref="hibernateTemplate"></property>??
  46. </bean>??
  47. </beans>??



?

下一步我們來看一下hibernateTemplate的使用:

?

[html]?view plaincopyprint?
  1. public?class?UserDAOImpl?implements?UserDAO?{??
  2. private?HibernateTemplate?hibernateTemplate;??
  3. public?HibernateTemplate?getHibernateTemplate()?{??
  4. return?hibernateTemplate;??
  5. }??
  6. public?void?setHibernateTemplate(HibernateTemplate?hibernateTemplate)?{??
  7. this.hibernateTemplate?=?hibernateTemplate;??
  8. }??
  9. public?void?save(User?user)?{??
  10. hibernateTemplate.save(user);??
  11. }}??



?

這基本上就是我們的hibernateTemplate原理及使用了,其實他的使用很簡單

?

下面,我們來看一下HibernateDaoSupport:

通過上面我們可以看出,通過xml注入hibernateTemplate,我們可以想象的到所有DAO類中都會有HibernateTemplate的bean方法,于是上面hibernateTemplate的set、get的方法和xml配置會有大量的,于是就出現了代碼冗余和重復,我們怎么才能避免這個重復呢,我們很容易應該能想到,把上面注入hibernateTemplate抽出一個類,然后讓我們的dao類來繼承這個類。不過這個類Spring已經有了,那就是HibernateDaoSupport,除此之外,HibernateDaoSupport也有SessionFactory的bean方法,所以我們在用HibernateDaoSupport的時候同樣也要給我們注入sessionfactory或者hibernateTemplate,在用的時候你會發現HibernateDaoSupport也給我們提供了getHibernateDaoSupport方法。

相關配置示例:userdao繼承了HibernateDaoSupport

?

?

[html]?view plaincopyprint?
  1. <bean?id="userdao"?class="com.bzu.dao.uerdao">??
  2. <property?name="sessionFactory"?ref="sessionFactory"></property>??
  3. </bean>??



?

?

? ? ?用上面的方法我們可以發現一個問題,我們同樣解決不了xml配置重復的問題,我們每一個dao都要在xml注入sessionfactory或者hibernateTemplate,解決這個問題的辦法就是我們自己在抽出一個SuperDao類,讓這個類去繼承HibernateDaoSupport,然后我們給SuperDao類去配置,這樣的話,我們在我的dao類中直接去繼承SuperDao類就可以了,這樣不管有多少dao類,只要繼承SuperDao,我們就可以實現我們想要的功能了。

轉載于:https://www.cnblogs.com/dengjiali/articles/3598637.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377262.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377262.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377262.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JDOJ-重建二叉樹

這是一道面試題&#xff0c;可以說是數據結構中的基礎題了&#xff0c;由先序遍歷以及中序遍歷生成一棵樹&#xff0c;然后輸出后序遍歷。 一個遞歸函數傳遞5個參數&#xff0c;頂點編號&#xff0c;先序左右區間&#xff0c;中序左右區間&#xff0c;每次進行區間長度判定&…

des算法密碼多長_密碼學中的多個DES

des算法密碼多長This is a DES that was susceptible to attacks due to tremendous advances in computer hardware in cryptography. Hence, it was a very complex or competent algorithm it would be feasible to reuse DES rather than writing an of cryptography. 由于…

《MySQL——索引筆記》

目錄回表覆蓋索引最左前綴原則聯合索引的時候&#xff0c;如何安排索引內的字段順序&#xff1f;索引下推重建索引問題聯合主鍵索引和 InnoDB 索引組織表問題in與between的區別回表 回到主鍵索引樹搜索的過程&#xff0c;我們稱為回表。 覆蓋索引 覆蓋索引就是在這次的查詢中…

計算凸多邊形面積的算法

1. 思路&#xff1a; 可以將凸多邊形&#xff08;邊數n > 3&#xff09;劃分為 (n - 2) 個三角形&#xff0c;分別運用向量叉積計算每個三角形的面積&#xff0c;最后累加各個三角形的面積就是多邊形的面積。 2. 求多邊形面積的算法模板&#xff1a;   定義點的結構體 str…

Windows CE開發常見問題解答

轉自&#xff1a; http://blog.csdn.net/slyzhang/article/details/6110490 1.怎樣在一個控件獲得焦點時打開軟鍵盤&#xff1f;比如一個EditBox獲得焦點后&#xff0c;這個時候自動打開軟鍵盤&#xff0c;這樣可以方便用戶輸入——SIPINFO、SHSIPINFO、SIPSETINFO、SIPGETINFO…

Julia中的supertype()函數

Julia| supertype()函數 (Julia | supertype() function) supertype() function is a library function in Julia programming language, it is used to get the concrete supertype of the given type (data type). supertype()函數是Julia編程語言中的庫函數&#xff0c;用于…

《操作系統知識點整理》

目錄進程與線程比較多線程同步與互斥生產者與消費者哲學家就餐問題讀者寫者問題進程間通信管道消息隊列共享內存信號量信號Socket鎖互斥鎖與自旋鎖讀寫鎖樂觀鎖與悲觀鎖死鎖進程與線程比較 進程是資源&#xff08;包括內存、打開的文件等&#xff09;分配的單位&#xff0c;線…

for,foreach,iterator的用法和區別

相同點&#xff1a; 三個都可以用來遍歷數組和集合不同點&#xff1a;1.形式差別 for的形式是 for&#xff08;int i0;i<arr.size();i&#xff09;{...} foreach的形式是 for&#xff08;int i&…

和菜鳥一起學linux總線驅動之初識spi驅動主要結構

既然知道了協議了&#xff0c;那么就可以開始去瞧瞧linux kenerl中的spi的驅動代碼了&#xff0c;代碼中有很多的結構體&#xff0c;還是對主要的結構體先做個了解吧&#xff0c;那樣才可以很好的理解驅動。主要是include/linux/spi.h 首先是SPI的主機和從機通信接口&#xff0…

操作系統大內核和微內核_操作系統中的內核

操作系統大內核和微內核A Kernel is the central component of an Operating System. The Kernel is also said to be the heart of the Operating System. It is responsible for managing all the processes, memory, files, etc. The Kernel functions at the lowest level …

《MySQL——鎖》

全局鎖是什么&#xff1f;全局鎖有什么用&#xff1f;全局鎖怎么用&#xff1f; 全局鎖主要用在邏輯備份過程中&#xff0c;對于InnoDB 引擎的庫&#xff0c;使用–single-transaction; MySQL 提供了一個加全局讀鎖的方法&#xff0c;命令是 Flush tables with read lock (FTW…

搜索引擎Constellio及Google Search Appliances connectors

做搜索產品的時候發現國外一個同類型的產品contellio&#xff0c;發現功能比較強大&#xff0c;先記錄下來 貌似可以添加文檔 網站 以及數據庫等不同類型的數據源 http://wiki.constellio.com/index.php/Main_Page http://www.constellio.com/ http://www.constellio.com htt…

dig下載_DIG的完整形式是什么?

dig下載DIG&#xff1a;副監察長 (DIG: Deputy Inspector General) DIG is an abbreviation of the Deputy Inspector General. It is a high-level position in the Indian Police Service. The officers who already offered service on Senior Superintendent of Police (SS…

分類器是如何做檢測的?——CascadeClassifier中的detectMultiScale函數解讀

原地址&#xff1a;http://blog.csdn.net/delltdk/article/details/9186875 在進入detectMultiScal函數之前&#xff0c;首先需要對CascadeClassifier做初始化。 1. 初始化——read函數 CascadeClassifier的初始化很簡單&#xff1a; cv::CascadeClassifier classifier; cl…

<MySQL>何時使用普通索引,何時使用唯一索引

如果能夠保證業務代碼不會寫入重復數據&#xff0c;就可以繼續往下看。 如果業務不能保證&#xff0c;那么必須創建唯一索引。 關于查詢能力 普通索引和唯一索引在查詢能力上是沒有很大差別的。 如&#xff1a;select id from T where k5 1、普通索引查找到滿足條件的第一個記…

Web版OutLook,利用POP接收郵件服務器郵件

一直想做一個Web版的OutLook&#xff0c;所以才萌生這個想法&#xff0c;其實以前也接觸過這方面的東西。于是上網找了找&#xff0c;漫天的都是Jmail來接收&#xff0c;好吧&#xff0c;既然大家都在用我也就下載下來試試了。 什么&#xff0c;怎么總是報錯呢&#xff1f;原來…

abs std::abs_ABS的完整形式是什么?

abs std::absABS&#xff1a;防抱死制動系統 (ABS: Anti-lock Braking System) ABS is an abbreviation of the Anti-lock Braking System. It is a safety anti-skid braking system that is used on a variety of aircraft, automobiles and other land vehicles, such as mo…

ubuntu 使用

shell 命令歷史搜索 &#xff1a; ctrl r使能 session 選擇界面&#xff1a;安裝gnome-session-fallback安裝lwqq轉載于:https://www.cnblogs.com/JonnyLulu/p/3600263.html

漢字速查使用方法簡介

《漢字速查》&#xff08;HanziSearcher&#xff09;是一個支持全漢字字典和詞典的檢索工具。其界面如下所示。 界面上方為工具欄。 左方為字典和詞典檢索欄。 右方在啟動時顯示版權信息和作者的聯系方式&#xff0c;在執行檢索時&#xff0c;顯示檢索結果。 檢索方法 漢字速查…

android jni示例_Android服務示例

android jni示例A service is a component that runs in the background for supporting different types of operations that are long running. The user is not interacted with these. These perform task even if application is destroyed. Examples include handling of…