Spring怎么在service控制事务

Spring如何在service控制事务?
   有2个Dao

UserDaoImpl:
public void saveUser(User user) {
   this.getHibernateTemplate().save(user);
   }

AcclDaoImpl:
public void saveAccl(Accl accl) {
   this.getHibernateTemplate().save(accl);
   }

Service层
UserServiceImpl:
private IUserDao userDao;
private IAcclDao acclDao;
public void saveUser(User user, Accl accl) {
   this.userDao.saveUser(user);
   this.acclDao.saveAccl(accl);
 }

 

applicationContext.xml:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="configLocation">
   <value>classpath:hibernate.cfg.xml</value>
   </property>
   </bean>
   <!--定义事务管理器-->
   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
   <property name="sessionFactory">
   <ref bean="sessionFactory"/>
   </property>
   </bean>
   <tx:advice id="smAdvice" transaction-manager="transactionManager">
   <tx:attributes>
   <tx:method name="save*" propagation="REQUIRED"/>
   <tx:method name="del*" propagation="REQUIRED"/>
   <tx:method name="update*" propagation="REQUIRED"/>
   </tx:attributes>
   </tx:advice>
   <aop:config>
   <aop:pointcut id="smMethod" expression="execution(* mm.s2sh.service.*.*(..))"/>
   <aop:advisor pointcut-ref="smMethod" advice-ref="smAdvice"/>
   </aop:config>

   <bean id="userAction" class="mm.s2sh.action.user.UserAction">
   <property name="userService" ref="userService"></property>
   </bean>
   <bean id="userService" class="mm.s2sh.service.user.impl.UserServiceImpl">
   <property name="userDao" ref="userDao"></property>
   <property name="acclDao" ref="acclDao"></property>
   </bean>
   <bean id="userDao" class="mm.s2sh.dao.user.impl.UserDaoImpl">
   <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
   <bean id="acclDao" class="mm.s2sh.dao.user.impl.AcclDaoImpl">
   <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>

  提交的时候发现数据没有进入数据库
  于是在Dao中save完后this.getSession().beginTransaction().commit();
  Accl表中有个字段是unique的,我故意提交了一个已有数据,结果导致User表中插入一条数据,也就是说没有回滚
   我感觉不应该用this.getSession().beginTransaction().commit();但是不用的话事务又没有提交进不了数据库
请问这个应该怎么弄才能做到正确回滚?

 

 

----------------解决方案--------------------

在service层加上这句话
@Transactional(readOnly = false)
有2个Dao
UserDaoImpl:
@Transactional(readOnly = false)
public void saveUser(User user) {
 this.getHibernateTemplate().save(user);
 }
AcclDaoImpl:
@Transactional(readOnly = false)
public void saveAccl(Accl accl) {
 this.getHibernateTemplate().save(accl);
 }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值