spring框架使用HibernateDaoSupport整合Hibernate框架

HibernateDaoSupport的作用

HibernateDaoSupportspring框架提供一個整合Hibernate框架的工具類,主要的功能是獲取數據庫配置文件併產生SessionFactory或者HibernateTemplate

HibernateDaoSupportAPI瞭解

protected  void

checkDaoConfig()
          Abstract subclasses must override this to check their configuration.
子類必須繼承此方法來檢查配置

protected  DataAccessException

 

convertHibernateAccessException(HibernateException ex)
          Convert the given HibernateException to an appropriate exception from the
org.springframework.dao hierarchy.將給定的HibernateException轉變爲一個來自dao層的合適的exception

protected  HibernateTemplate

createHibernateTemplate(SessionFactory sessionFactory)
          Create a HibernateTemplate for the given SessionFactory.
爲給定的SessionFactory創建一個HibernateTemplate對象

 HibernateTemplate

getHibernateTemplate()
          Return the HibernateTemplate for this DAO, pre-initialized with the SessionFactory or set explicitly.
返回該dao已預先初始化或者明確賦值SessionFactoryHibernateTemplate對象。

protected  Session

getSession()
          Obtain a Hibernate Session, either from the current transaction or a new one.
從當前事務或者新的事務中得到一個Hibernate Session

protected  Session

getSession(boolean allowCreate)
          Obtain a Hibernate Session, either from the current transaction or a new one.allowCreate
變量表示是否允許從新的事務中得到一個Session,默認爲true

 SessionFactory

getSessionFactory()
          Return the Hibernate SessionFactory used by this DAO.
從此Dao中返回一個Hibernate SessionFactory

protected  void

releaseSession(Session session)
          Close the given Hibernate Session, created via this DAO's SessionFactory, if it isn't bound to the thread (i.e. isn't a transactional Session).
釋放由此Dao創建的連接在線程中的Session,這不會報錯,是非常安全的做法

 void

setHibernateTemplate(HibernateTemplate hibernateTemplate)
          Set the HibernateTemplate for this DAO explicitly, as an alternative to specifying a SessionFactory.
爲此Dao設置HibernateTemplate來確定一個SessionFactory

 void

setSessionFactory(SessionFactory sessionFactory)
          Set the Hibernate SessionFactory to be used by this DAO.
設置此Dao中使用的SessionFactory



使用HibernateDaoSupport整合Hibernate簡單例子


步驟

1.需要一個配置文件關聯實體類屬性和表的列名以及定義主鍵及其生成策略,例如Event.hbm.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPEhibernate-mapping PUBLIC

"-//Hibernate/HibernateMapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--package屬性值爲實體類所在包-->

<hibernate-mapping package="com.zky.entity">

         <!--classname屬性即爲類名,id標籤表示表的主鍵-->

         <class name="Event" table="EVENTS">

                   <!--name屬性表示實體類中的屬性名,column屬性表示表中的列名-->

                   <id name="id"column="EVENT_ID">

                            <generator class="increment"/>

                   </id>

                   <property name="date"type="timestamp" column="EVENT_DATE"/>

                   <property name="title" column="EVENT_TITLE"/>

         </class>

</hibernate-mapping>

2.需要一個與表關聯的實體類,用於存儲信息

package com.zky.entity;

 

import java.util.Date;

 

/**

 * @author Blank

 *

 */

public class Event {

         privatelong id;

         privateString title;

         privateDate date;

         publiclong getId() {

                   returnid;

         }

         publicvoid setId(long id) {

                   this.id = id;

         }

         publicString getTitle() {

                   returntitle;

         }

         publicvoid setTitle(String title) {

                   this.title = title;

         }

         publicDate getDate() {

                   returndate;

         }

         publicvoid setDate(Date date) {

                   this.date = date;

         }

         @Override

         publicString toString() {

                   return"Event [id=" + id + ",title=" + title + ", date=" + date+ "]";

         }

        

}

3.需要一個配置文件配置數據庫連接信息,並將上面的關聯文件導入並生效。例如hibernate.cfg.xml

<?xmlversion='1.0' encoding='utf-8'?>

<!DOCTYPEhibernate-configuration PUBLIC

"-//Hibernate/HibernateConfiguration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

         <session-factory>

                   <!-- Database connection settings -->

                   <property name="connection.driver_class"

                            >com.mysql.jdbc.Driver</property>

                   <property name="connection.url"

                            >jdbc:mysql://localhost:3306/hibernatedaosupport</property>

                   <property name="connection.username"

                            >root</property>

                   <property name="connection.password"

                            >13116516681</property>

                   <!-- JDBC connection pool (use the built-in)-->

                   <property name="connection.pool_size"

                            >1</property>

                   <!-- 設置SQL 方言 -->

                   <property name="dialect"

                            >org.hibernate.dialect.HSQLDialect</property>

                   <!-- Disable the second-level cache -->

                   <property name="cache.provider_class"

                            >org.hibernate.cache.NoCacheProvider</property>

                   <!-- Echo all executed SQL to stdout -->

                   <property name="show_sql"

                            >true</property>

                   <!-- Drop and re-create the database schemaon startup -->

                   <property name="hbm2ddl.auto"

                            >update</property>

                   <!--加載hbm.xml-->

                   <mapping resource="com/zky/entity/Event.hbm.xml"/>

                  

         </session-factory>

</hibernate-configuration

> 

4.Hibernate作用於dao層,所以需要一個dao層繼承HibernateDaoSupport的實現類,例如EventDaoImpl.java

import java.util.Date;

 

importjavax.annotation.Resource;

 

import org.hibernate.Session;

importorg.hibernate.SessionFactory;

importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

importcom.zky.dao.IEventsDao;

import com.zky.entity.Event;

 

/**

 * @author Blank

 *

 */

 

public class IEventsDaoImpl extends HibernateDaoSupport implements IEventsDao {

 

        

         @Resource

         publicvoid setFactory(SessionFactoryfactory) {

                   super.setSessionFactory(factory);

                   this.checkDaoConfig();

         }

 

 

         @Override

         publicvoid insert(Event event) {

                   //TODOAuto-generated method stub

                   //獲取由當前daoSessionFactory得到的Session

                   Session session = super.getHibernateTemplate().getSessionFactory().openSession();

                   event.setDate(new Date());

                   session.save(event);

                   session.beginTransaction().commit();

                   session.close();

         }

 

}

 

5.Spring配置文件讀取hibernate.cfg.xml並由該配置實例化SessionFactory對象

<?xmlversion="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" 

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

        xmlns:context="http://www.springframework.org/schema/context" 

        xmlns:mvc="http://www.springframework.org/schema/mvc" 

        xmlns:util="http://www.springframework.org/schema/util"

       xsi:schemaLocation=" 

         http://www.springframework.org/schema/beans 

         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 

         http://www.springframework.org/schema/context 

         http://www.springframework.org/schema/context/spring-context-3.0.xsd 

         http://www.springframework.org/schema/mvc     

         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 

         http://www.springframework.org/schema/util  

         http://www.springframework.org/schema/util/spring-util-3.0.xsd"> 

 

     <!-- 開啓context的註解功能(隱式開啓) -->        

     <context:annotation-config/>

    

     <!-- 開啓mvc的註解功能,並定義所有的Controller可用的validator -->

     <mvc:annotation-driven/>   

    

     <!-- 掃描事務層和控制器層,將帶有標註註釋的類實例化 -->

         <context:component-scan base-package="com.zky.controller"></context:component-scan>

       <context:component-scanbase-package="com.zky.service.impl"></context:component-scan>

         <!-- 設置跳轉路徑的默認前綴和後綴-->

         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

             <propertyname="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

             <propertyname="suffix" value=".jsp"></property>

    </bean>

    <!—讀取hibernate.cfg.xml來實例化SessionFactory-->

    <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

                <property name="configLocations"

                        value="classpath:hibernate.cfg.xml">

                </property>

        </bean>

        <!--實例化iEventDao,併爲setFactory方法依賴注入SessionFactory-->

        <bean id="iEventDao" class="com.zky.dao.impl.IEventsDaoImpl" >

                 <property name="factory">

                           <ref bean="sessionFactory"/>

                 </property>    

        </bean>

</beans>

6.web.xml加載spring框架

<?xmlversion="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

         <display-name>HibernateDaoSupportDemo</display-name>

         <welcome-file-list>

                   <welcome-file>index.html</welcome-file>

                   <welcome-file>index.htm</welcome-file>

                   <welcome-file>index.jsp</welcome-file>

                   <welcome-file>default.html</welcome-file>

                   <welcome-file>default.htm</welcome-file>

                   <welcome-file>default.jsp</welcome-file>

         </welcome-file-list>

 

         <filter>

 

                   <filter-name>SetCharacterEncoding</filter-name>

 

                   <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class>

 

 

                   <init-param>

 

                            <param-name>encoding</param-name>

 

                            <param-value>UTF-8</param-value>

 

                   </init-param>

 

 

                   <init-param>

 

                            <param-name>forceEncoding</param-name>

 

                            <param-value>true</param-value>

 

                   </init-param>

 

         </filter>

 

 

         <filter-mapping>

 

                   <filter-name>SetCharacterEncoding</filter-name>

 

                   <url-pattern>/*</url-pattern>

 

         </filter-mapping>

 

 

         <context-param>

 

                   <param-name>contextConfigLocation</param-name>

 

                   <param-value>/WEB-INF/spring-servlet.xml</param-value>

 

         </context-param>

 

         <!-- 加載spring框架 -->

 

 

 

         <servlet>

 

                   <servlet-name>spring</servlet-name>

 

                   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

 

         </servlet>

 

         <!-- 設置spring框架的適用請求地址 -->

 

 

 

         <servlet-mapping>

 

                   <servlet-name>spring</servlet-name>

 

                   <url-pattern>*.do</url-pattern>

 

         </servlet-mapping>

</web-app>

運行結果

tomcat運行該項目後,每次調用EventDaoImpl類中的insert方法後,數據庫表EVENTS都會多出一條記錄



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章