Spring @Transactional回滚无效

时间:2018-04-28 10:15:48

标签: spring spring-mvc

@RestController
@RequestMapping("/Api/Order")
public class OrderController {

    private OrderService service;
    private RefundService refundService;

    @AsCustomer
    @DeleteMapping(value = "/{orderID}/RefundApplication")
    @Transactional(rollbackFor = RuntimeException.class)
    public Map cancelRefundApplication(@SessionAttribute("user") User user,
                                       @PathVariable("orderID") String orderID) {
        Order order = service.getOrderByID(orderID);
        RefundApplication application = refundService.get(orderID);
        order.setState(Order.STATE_PAYED);
        refundService.delete(orderID);
        service.updateOrder(order);
        throw new EntityNotFoundException("test");
    }
    ...

我希望在抛出RuntimeException时回滚在cancelRefundApplication方法中创建的事务,如果没有抛出RuntimeException则要提交。但是我发现即使抛出RuntimeException,事务也不会回滚。对于测试perpose,我更改代码以使其始终抛出EntityNotFoundException,并使用以下测试方法对其进行测试。运行测试后,我检查数据库并查找退款应用程序数据已删除,这意味着事务未回滚且@Transactional注释无效。

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {WebConfig.class, RootConfig.class, DataConfig.class})
@WebAppConfiguration
class OrderControllerTest {

    @Autowired
    OrderController controller;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    AppWideExceptionHandler exceptionHandler;
    private User customer;
    private User seller;
    private HashMap<String, Object> sessionAttrs;
    private ResultMatcher success = jsonPath("$.code")
            .value("0");
    private MockMvc mockMvc;

    @Test
    void cancelRefundApplication() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        String path = String.format("/Api/Order/%s%d0001/RefundApplication"
                , simpleDateFormat.format(new Date()), customer.getID());
        mockMvc.perform(delete(path)
                .characterEncoding("UTF-8")
                .sessionAttrs(sessionAttrs))
                .andDo(print())
                .andExpect(success);
    }
    ...

这是DataConfig类:

@Configuration
@MapperScan("youshu.mapper")
public class DataConfig {

    @Bean
    public DataSource dataSource() {
//        org.apache.ibatis.logging.LogFactory.useLog4J2Logging();
        PooledDataSource pds = new PooledDataSource();
        pds.setDriver("com.mysql.cj.jdbc.Driver");
        pds.setUsername(...);
        pds.setPassword(...);
        pds.setUrl("jdbc:mysql://XXXX/ys_ljn?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false");
        return pds;
    }

    @Bean
    public JdbcOperations jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setTypeAliasesPackage("youshu.entity");
        return sessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionTemplate sqlSession(SqlSessionFactory factory){
        return new SqlSessionTemplate(factory);
    }

}

2 个答案:

答案 0 :(得分:0)

检查测试中是否包含TransactionalTestExecutionListener,如果不添加:@TestExecutionListeners(listeners = {TransactionalTestExecutionListener.class})

答案 1 :(得分:0)

需要通过使用@EnableTransactionManagement

注释配置类来手动启用事务