当使用spring整合hibernate时,需要将hibernate的事务转交给spring来管理,DAO层需要实现一个接口,但设置bean时仍然是设置实现的DAO类。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd "> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean> <bean id="QqUserDAO" class="com.zuo.hib.QqUserDAO"> <property name="sessionFactory" ref="sessionFactory"></property> <!--<property name="hibernateTemplate" ref="hibernateTemplate"></property>--> </bean> <!-- 配置hibernate操作模板类 ,不声明HibernateTemplate时需要继承HibernateDaoSupport类--> <!--<bean name="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>--> <!-- 定义事务管理器,从Hibernate中接手事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 定义事务规则 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <!-- 定义事务入口 --> <aop:config> <aop:pointcut id="allDaoMethod" expression="execution(* com.zuo.hib.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethod" /> </aop:config> </beans>