@PostConstruct方法上的@Transactional [英] @Transactional on @PostConstruct method

查看:155
本文介绍了@PostConstruct方法上的@Transactional的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在应用程序的开头阅读文本数据夹具(CSV文件),并将其放入数据库中.

I want to read text data fixtures (CSV files) at the start on my application and put it in my database.

为此,我用初始化方法( @PostConstruct 批注)创建了一个 PopulationService .

For that, I have created a PopulationService with an initialization method (@PostConstruct annotation).

我还希望它们在单个事务中执行,因此我在同一方法上添加了 @Transactional .

I also want them to be executed in a single transaction, and hence I added @Transactional on the same method.

但是, @Transactional 似乎被忽略了: 在我的底层DAO方法中开始/停止了事务.

However, the @Transactional seems to be ignored : The transaction is started / stopped at my low level DAO methods.

然后我需要手动管理交易吗?

Do I need to manage the transaction manually then ?

推荐答案

这可能会有所帮助(

this might be helpful (http://forum.springsource.org/showthread.php?58337-No-transaction-in-transactional-service-called-from-PostConstruct):

在@PostConstruct中(与InitializingBean接口中的afterPropertiesSet一样),无法确保已完成所有后期处理,因此(实际上)不能有任何事务.确保工作正常的唯一方法是使用TransactionTemplate.

In the @PostConstruct (as with the afterPropertiesSet from the InitializingBean interface) there is no way to ensure that all the post processing is already done, so (indeed) there can be no Transactions. The only way to ensure that that is working is by using a TransactionTemplate.

因此,如果您希望在事务中执行@PostConstruct中的某些内容,则必须执行以下操作:

So if you would like something in your @PostConstruct to be executed within transaction you have to do something like this:

@Service("something")
public class Something {

    @Autowired
    @Qualifier("transactionManager")
    protected PlatformTransactionManager txManager;

    @PostConstruct
    private void init(){
        TransactionTemplate tmpl = new TransactionTemplate(txManager);
        tmpl.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                //PUT YOUR CALL TO SERVICE HERE
            }
        });
   }
}

这篇关于@PostConstruct方法上的@Transactional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆