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();但是不用的话事务又没有提交进不了数据库
请问这个应该怎么弄才能做到正确回滚,第一次配S2SH,见笑了
------解决方案--------------------
在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);
}
好像是这样 我也不是很清楚