在Spring中集成Hibernate事务

来源:互联网 发布:java生成二维码简单吗 编辑:程序博客网 时间:2024/05/22 00:33
在Spring中集成Hibernate事务非常简单,只需配置一下spring的applicationContext.xml文件,配置文件的主体部分如下:
<!-- 配置数据源 -->
<bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName"
   value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>
 <!-- 配置sessionFactory  -->
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="lobHandler">
   <ref local="defaultLobHandler" />
  </property>
  <property name="dataSource">
   <ref bean="dataSource" />
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">
     ${hibernate.dialect}
    </prop>
    <prop key="hibernate.show_sql">
     ${hibernate.show_sql}
    </prop>
    <prop key="hibernate.jdbc.batch_size">
     ${hibernate.jdbc.batch_size}
    </prop>
    <prop key="hibernate.query.factory_class">
     ${hibernate.query.factory_class}
    </prop>
    <prop key="hibernate.cache.provider_class">
     ${hibernate.cache.provider_class}
    </prop>
    <prop key="hibernate.cache.use_query_cache">
     ${hibernate.cache.use_query_cache}
    </prop>
   </props>
  </property>
 
<!-- 配置从HibernateDaoSupport派生自定义的子类HibernateBookDao  -->
  <bean id="HibernateBookDao"
  class="com.dao.HibernateBookDao">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>

 <!-- Transaction manager for a Hibernate DataSource-->
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref local="sessionFactory" />
  </property>
 </bean>

 <!-- the transactional advice for privilege service -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <!-- the transactional semantics... -->
  <tx:attributes>
   <!-- all methods starting with 'get' or 'find' are read-only -->
   <tx:method name="get*" read-only="true" />
   <tx:method name="find*" read-only="true" />
   <!-- all methods starting with 'update' or 'insert' or 'delete' will use the default transaction settings (see below) -->
   <tx:method name="update*" />
   <tx:method name="insert*" />
   <tx:method name="save*" />
   <tx:method name="delete*" />
  </tx:attributes>
 </tx:advice>

 <!-- ensure that the above transactional advice runs for any execution
  of an operation defined by the Service interface. All service object end with
  BO and under package com.hacongz. will match the pointcut
  
  声明的事务对象必须是接口,而不是实现
 -->
 <aop:config>
  <aop:pointcut id="serviceOperation"
   expression="execution(* com.hacongz..*Impl.*(..))" />
  <aop:advisor advice-ref="txAdvice"
   pointcut-ref="serviceOperation" />
 </aop:config>