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());
}
}
测试测试…
通过通过…
以上是Spring与Hibernate的整合。
从此Struts2 + Spring + Hibernate框架搭建起来啦.(加上前面几篇)
=============================================================================
下一篇:总结配置文件----配置文件实例