当前位置: 代码迷 >> J2EE >> Spring事务配置给service 还是 dao?该怎么处理
  详细解决方案

Spring事务配置给service 还是 dao?该怎么处理

热度:653   发布时间:2016-04-22 01:16:31.0
Spring事务配置给service 还是 dao?
最近学习spring ,也做了一些例子,

但是有个困惑就是,采用 spring的事务管理的时候,这样配置:
XML code
<!--  配置事务管理器 -->    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">        <property name="sessionFactory">            <ref bean="sessionFactory" />        </property>    </bean>    <!--  配置事务的传播特性 -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="save*" propagation="REQUIRED" />            <tx:method name="add*" propagation="REQUIRED" />            <tx:method name="delete*" propagation="REQUIRED" />            <tx:method name="modify*" propagation="REQUIRED" />            <tx:method name="update*" propagation="REQUIRED" />            <tx:method name="*" read-only="true" />        </tx:attributes>    </tx:advice>    <!--  那些类的哪些方法参与事务 -->    <aop:config>        <aop:pointcut id="allManagerMethod" expression="execution(* my.idao.*.*.*(..))" />        <aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice" />    </aop:config>        <bean id="sessionAdvice" class="my.filter.FlexSessionInterceptor" />    <!-- 配置自动代理 -->    <bean id="beanNameAutoProxyCreator"    class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">    <property name="beanNames">       <list>        <value>formDesignerService</value>       </list>    </property>    <property name="interceptorNames">       <value>sessionAdvice</value>    </property>    </bean>


 expression="execution(* my.idao.*.*.*(..)) 对于这一块的配置还是不太明白,因为 我觉得事务开启的话也是针对业务的,而不是dao,
但是我找了许多例子,几乎都是这样配置的,有些虽然是把 service的方法配置成事务,但是没有dao接口,也就是在service的方法下面把所有的操作都包含了,包括对数据库的操作,所以很困惑---到底应该是针对业务来配置 事务 ,还是 针对 dao来配置事务?

------解决方案--------------------
service
------解决方案--------------------
我觉得应该给service
------解决方案--------------------
我觉得事务处理应该写在service中, 而不应该写在dao 当中, 用service调用dao, 
可能你那个系统没有写service, 直接就用dao 了
------解决方案--------------------
这要看你的事务边界在哪里了。一般来说,事务边界不会位于 DAO 上,会被定义在一个业务逻辑方法之上,因为一个业务逻辑方法会调用多个 DAO 的方法而完成一个事务。
------解决方案--------------------
service,举个例子,某service方法里包含了两个插入数据库操作,这两个操作是调用了dao层的方法,这样的话如果是给dao层加事务,当第二个操作出错时,第一个操作能回滚么?这样的例子很多的。
------解决方案--------------------
事务配置service中方法 ,因为service中是实现业务每个业务是一个整体,不能只执行一半
比如service中有一个方法转账 transferofaccount()现在从A卡转账到B卡
transferofaccount(){
dao.update(A);//A卡减200
dao.update(B);//B卡加200
}
那么这必须用事务控制否则中途出现问题A减200而B没有加200
------解决方案--------------------
service
  相关解决方案