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都会多出一条记录



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