您好我正在尝试用事务开发spring和hibernate应用程序,我使用spring 4.x和hibernate 4.x,这是我的代码片段
的applicationContext.xml
<tx:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.xyx.service" />
<context:component-scan base-package="com.xyz.dao" />
<import resource="conf/spring/persistence.xml" />
servlet的context.xml中
<context:component-scan base-package="com.xyx.webservice.components" />
<mvc:annotation-driven />
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
<!-- Configure to plugin JSON as request and response in method handler -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter"/>
</list>
</property>
</bean>
persistance.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/xyx" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="packagesToScan" value="com.xyz.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
</props>
</property>
</bean>
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref= "sessionFactory" >
</bean>
</beans>
和finnaly meservice看起来像这样
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=RuntimeException.class)
public Object loadCategories(UserContactsInputVO inputVo) {
User user= getUserObject(inputVo);
userDAO.saveOrUpdateForTrancasction(user);
System.out.println(user.getUserId());
//getAudioFilesBasedOnCategories();
try{
return getAudioFilesBasedOnCategories();
}catch (RuntimeException e) {
e.printStackTrace();
}
return new CategoryResponseVo();
}
和
@Transactional(propagation=Propagation.REQUIRED)
public CategoryResponseVo getAudioFilesBasedOnCategories()
{
try{
if(true)
throw new RuntimeException();
}finally{
}
return vo;
}
此处发生运行时异常,但不会回滚db记录。
答案 0 :(得分:2)
事务未被回滚的原因是因为RuntimeException没有传播到管理事务回滚代码的实际Spring代理。它没有被传播的原因是你已经抓住它并且没有被重新播放。
try{
return getAudioFilesBasedOnCategories();
}catch (RuntimeException e) {
e.printStackTrace(); //**THIS IS WRONG**
}
而是这样做
try{
return getAudioFilesBasedOnCategories();
}catch (RuntimeException e) {
//log the error
throw e; // throw back
}
此外,您可能不需要在RuntimeException上默认提供rollbackFor属性,该事务将被回滚。