Java Spring @Transactional方法在抛出异常时不回滚

时间:2016-01-28 09:01:22

标签: spring mybatis transactional

我的配置代码在这里:

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySource(value="classpath:datasource.properties")
public class DataSourceConfig {

    @Autowired private Environment env;

    @Bean(destroyMethod="close")
    public BasicDataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(env.getProperty("db.driverClass"));
        ds.setUrl(env.getProperty("db.url"));
        ds.setUsername(env.getProperty("db.username"));
        ds.setPassword(env.getProperty("db.password"));
        ds.setInitialSize(Integer.valueOf(env.getProperty("db.initialSize")));
        return ds;
    }

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

}

@Transactional方法:

@Override
    @Transactional
    public void create(String orderid, String type, String userid,
            String comment) throws Exception {
        log.info("### orderid={}, type={}, userid={}, comment={}", 
                orderid, type, userid, comment);
        OrderActivity orderActivity = new OrderActivity();
        orderActivity.setActivityid(SeqUtil.produceOrderActivityid());
        orderActivity.setComment(comment);
        orderActivity.setOperator(userid);
        orderActivity.setOrderid(orderid);
        orderActivity.setType(type);
        orderactivityDao.insert(orderActivity);
        //FIXME just for test
        if(OrderConstant.ACTIVITY_CANCEL.equals(type)){
            throw new RuntimeException();
        }
        log.info("###orderActivity=[{}]", orderActivity);
    }

在方法 create 中,当 type 为ACTIVITY_CANCEL时,则抛出异常。但是这个活动也被插入到数据库中,而不是回滚。为什么呢?

1 个答案:

答案 0 :(得分:0)

我明白了。我把AppConfig和b放在DataSourceConfig的不同上下文中。改变了这样的代码:

this.setState

然后一切都好。