SSH框架搭建过程---之Spring-Hibernate整合(5)

Spring-Hibernate整合

整合后的结构具有以下特点:

  • Spring直接接管理对SessionFactory对象的管理,不再需要编写获取SessionFactory对象的实用工具类。
  • 将Hibernate配置信息直接整合到Spring的SessionFactory Bean 的定义中,不再需要Hibernate配置文件。
  • 使用HibernateTemplateBean直接接管了Hibernate中的Session对象,对数据的访问通过HibernateTemplate的API实现。
  • 使用HibernateTemplate访问数据时,不需要再定义和事务相关的语句,如开始、提交、回滚事物以及进行异常处理。
  • 上述所有资源均以Spring Bean的形式体现,可方便的实现注入。

1.  修改ApplicationContext.xml文件

a)   Spring直接接管理对SessionFactory对象的管理

<bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
       <property name="dataSource" ref="dataSource" />
       <property name="mappingResources">
           <list>
              <value>cn/edu/bucea/domain/Demo.hbm.xml</value>
           </list>
       </property>
       <property name="hibernateProperties">
           <props>
               <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
               <prop key="hibernate.show_sql">true</prop>
               <prop key="hibernate.format_sql">true</prop>
           </props>
       </property>
</bean>


 

b)   Spring使用HibernateTemplate Bean直接接管了Hibernate中的Session对象

 

  

  <bean id="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">
       <property name="sessionFactory"ref="sessionFactory" />
    </bean>

 

c)   将jdbcTemplate即Spring与Hibernate整合前的相关代码注释掉。

d)   修改配置文件DAO组件中的注入对象

例:

<bean id="demoDAO"class="cn.edu.bucea.DAO.DemoDAO">
    <property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>


 

2.  修改注入对象,修改DAO组件中访问数据库的方法,即单独使用Spring访问数据库的方法改为整合后的方法。

private HibernateTemplate hibernateTemplate;
public voidsetHibernateTemplate(HibernateTemplate hibernateTemplate) {
       this.hibernateTemplate = hibernateTemplate;
}
…
public void saveDemo(Demodemo) throws DemoException {
       try{
           hibernateTemplate.save(demo);
       } catch(DataAccessExceptione){
           throw new DemoException("保存信息出错。" + e.getMessage());
       }
}


 

 

测试测试…

通过通过…

 

以上是SpringHibernate的整合。

 

从此Struts2 + Spring + Hibernate框架搭建起来啦.(加上前面几篇)

=============================================================================

下一篇:总结配置文件----配置文件实例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值