Spring Hibernate使用TransactionInterceptor声明式事务配置

<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory">
         <ref bean="sessionFactory"/>
     </property>
</bean>
<!-- 事务拦截器,激活事务管理器所必须的bean -->
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager">
            <ref bean="transactionManager" />
        </property> 
        <!-- 配置事务属性 -->
        <property name="transactionAttributes">
           <props>
              <prop key="delete*">PROPAGATION_REQUIRED</prop>
              <prop key="add*">PROPAGATION_REQUIRED</prop>
              <prop key="update*">PROPAGATION_REQUIRED</prop>
              <prop key="save*">PROPAGATION_REQUIRED</prop>
              <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
          </props>
       </property>
     </bean>
     <!-- 定义事务处理代理bean,他需要两个属性,一个是指定需要代理的bean,另一个是代理bean所需的事务拦截器 -->
     <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames">
           <list>
              <value>tempService</value>
           </list>
        </property>
        <property name="interceptorNames">
           <list>
              <value>transactionInterceptor</value>
           </list>
        </property>
     </bean>
    <!-- 业务逻辑层 -->
<bean id="tempService"
  class="com.cj.transaction.service.TempService" abstract="false"
  lazy-init="default" autowire="default" dependency-check="default">
  <property name="userDAO">
   <ref bean="userDAO" />
  </property>
  <property name="deptDAO">
   <ref bean="deptDAO" />
  </property>
</bean>
<bean id="userDAO" class="com.cj.transaction.hibernate.UserDAO">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
</bean>
<bean id="deptDAO" class="com.cj.transaction.hibernate.DeptDAO">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
</bean>

如果模块过多话,可以考虑用自动创建事务代理的方式
    <!-- 自动代理 -->
    <bean id="autoproxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
       <property name="beanNames">
          <list>
             <value>*Service</value>
          </list>
       </property>
       <property name="interceptorNames">
          <list>
             <value>transactionInterceptor</value>
          </list>
       </property>
    </bean>

你可能感兴趣的:(spring,Hibernate)