AlpacaMan
AlpacaMan

Reputation: 513

Spring @Transactional rollback not working

@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");
    }
    ...

I want transaction created in cancelRefundApplication method to be rolled back when a RuntimeException is thrown, and to be commit if no RuntimeException is thrown. But I find the transaction is not rolled back even if a RuntimeException is thrown. For test perpose, I change the code to make it always throw a EntityNotFoundException, and test it with following test method. After running the test, I check database and find refund application data is deleted, which means transaction is not rolled back and @Transactional annotation is not working.

@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);
    }
    ...

This is DataConfig class:

@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");
        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);
    }

}

Upvotes: 0

Views: 2446

Answers (2)

AlpacaMan
AlpacaMan

Reputation: 513

Transactions need to be enabled manually by annotating config class with @EnableTransactionManagement

Upvotes: 1

borino
borino

Reputation: 1750

Check include or not TransactionalTestExecutionListener in your test, if not add: @TestExecutionListeners(listeners = {TransactionalTestExecutionListener.class})

Upvotes: 0

Related Questions