SSH整合(二)-Spring整合Hibernate

来源:互联网 发布:java web开发案例精粹 编辑:程序博客网 时间:2024/05/19 18:48
上篇文章说到Spring整合Hibernate共有三种数据源配置, 并介绍了dbcp的配置方式(有空我会将剩下的c3p0和proxool补全),接下来我们将开始整合Spring和Hibernate

开始之前说明一下整合Spring和Hibernate用到最小集合的包

  

使用XML的方式整合Spring和Hibernate

(一)整合SessionFactory用到LocalSessionFactoryBean

<bean id="sessionFactory“ class=“org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mappingResources"><list><value>com/chapter5/orm/User.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></props></property></bean>

(二)整合事务
通过定义切面,指定事务边界

<aop:config><aop:pointcut id="userServiceMethods" expression="execution(* com.chapter5.service.*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="userServiceMethods"/></aop:config> 

定义事务管理器,并注入sessionFactory

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

txAdvice指定定义好的事务管理器,并且定义对应方法下面事务的传播属性,所有的方法都支持当前事务,如果当前没有事务,就以非事务的方式运行(SUPPORTS),increasePrice开始的方法支持当前事务,如果当前没有事务,就新建一个事务(Required)

<tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="increasePrice*" propagation="REQUIRED"/>      <tx:method name="*" propagation="SUPPORTS" read-only="true"/></tx:attributes></tx:advice>

使用Annotation的方式整合Spring和Hibernate

(一)整合SessionFactory用到AnnotationSessionFactoryBean

<bean id="sessionFactory“ class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="annotatedClasses"><list><value>com.bjsxt.model.User</value><value>com.bjsxt.model.Log</value></list></property><property name="hibernateProperties"><props><prop key="hibernate.dialect“>org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop></props></property></bean>

可以通过扫描包的方式定义annotatedClasses

<property name=“packagesToScan"><list><value>com.bjsxt.model</value></list></property>

(二)整合事务
定义事务管理器

<bean id="txManager“ class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean>

指定框架需要的事务管理器

<tx:annotation-driven transaction-manager="txManager"/>

Spring对Hibernate的封装

Spring提供了HibernateTemplate和HibernateDaoSupport,封装Hibernate的API, 方便对Hibernate的调用。
(一)HibernateTemplate的配置

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

需要使用HibernateTemplate, 将HibernateTemplate注入要使用的类里,HibernateTemplate使用了Template模式,关于设计模式,将会在另外的专题里总结

总结


大多数配置方案会选择在整合sessionFactory的时候使用Annotation的方式,在整合事务的时候使用xml的方式。这样选择的好处是可以尽量少配置,方便管理。

                                             
0 0
原创粉丝点击