07年11月15日
我目前做的项目是采用struts+hibernate+spring框架来做的,这个架构是支持hibernate延迟的,即lazy="true";
一般采用这个架构都要配service层,就不再唠叨了.关键是看一个配置文件能说明service层的作用.看看配置文件
<?
xml version="1.0" encoding="UTF-8"
?>
<!
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"
>

<
beans
>
<
bean
id
="channleManagerServiceTarget"
class
="com.cms.channle.service.impl.ChannleManager"
singleton
="true"
>
<
property
name
="tchannleDAO"
>
<
ref
local
="tchannleDAO"
/>
</
property
>
</
bean
>

<
bean
id
="channleManageService"
class
="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
>
<
property
name
="transactionManager"
>
<
ref
bean
="transactionManager"
/>
</
property
>
<
property
name
="target"
>
<
ref
local
="channleManagerServiceTarget"
/>
</
property
>
<
property
name
="transactionAttributes"
>
<
props
>
<
prop
key
="list*"
>
PROPAGATION_REQUIRED,readOnly
</
prop
>
<
prop
key
="add*"
>
PROPAGATION_REQUIRED
</
prop
>
<
prop
key
="delete*"
>
PROPAGATION_REQUIRED
</
prop
>
<
prop
key
="del*"
>
PROPAGATION_REQUIRED
</
prop
>
<
prop
key
="save*"
>
PROPAGATION_REQUIRED
</
prop
>
<
prop
key
="get*"
>
PROPAGATION_REQUIRED,readOnly
</
prop
>
<
prop
key
="update*"
>
PROPAGATION_REQUIRED
</
prop
>
<
prop
key
="edit*"
>
PROPAGATION_REQUIRED
</
prop
>
</
props
>
</
property
>
<
property
name
="postInterceptors"
>
<
list
>
<
ref
bean
="hibernateInterceptor"
></
ref
>
</
list
>
</
property
>
</
bean
>

<
bean
id
="tchannleDAO"
class
="com.cms.channle.dao.impl.TchannleDAO"
>
<
property
name
="sessionFactory"
>
<
ref
bean
="sessionFactory"
/>
</
property
>
</
bean
>

</
beans
>
上面代码中<property name="transactionAttributes"></property >之间是对service层配置了事务,由spring管理.
struts的action里调用的时候,一般都调用service层封装的方法.因为service层的方法可能会调用多个DAO层的方法.
举个例子说明一下,假入说我有一个需求,就是银行的转帐需求吧,当A给B汇款1000元这个过程,A的帐户里应该减少1000元,B的帐户应该增加1000元,而这个过程是由2个DAO方法实现的,即A减少的方法,B增加的方法.而service层的转帐方法(起名叫getResult方法)里面先调用了DAO层A减少的方法,再调用B增加的方法.配置文件的事务配置的是管理service层的事务,只有service层的转帐方法完成了DAO层的两个方法,才算这个事务结束.如果直接调用DAO层的方法,那么spring不会管理事务,每次调用DAO的方法就算单独的一个事务,如果程序运行不稳定,A减少1000元的方法成功,B增加1000元的方法失败的情况下,由于此时的事务不是同一个事务.那么A的事务不会回滚.....结果就是数据库里面A少了1000块钱,B没有增加1000块钱........钱那里去了........出大错了吧,这个错误够严重了吧!