如何将事务获取到@PostConstruct CDI bean 方法 [英] How to get transactions to a @PostConstruct CDI bean method

查看:20
本文介绍了如何将事务获取到@PostConstruct CDI bean 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验 Java EE 7、CDI、JPA 和 JSF.

I'm experimenting with Java EE 7, CDI, JPA and JSF.

当 webapp 启动时,我想在我的 CDI bean(用@PostConstruct 标记)中运行一个初始化方法,它对数据库做一些工作(插入一些行等).为此,我需要一笔交易,但这并不像我预期的那么容易.

When the webapp starts, I would like to run an initialization method in my CDI bean (marked with @PostConstruct) that does some work with the database (inserts some rows etc..). For this I need a transaction, but this wasn't as easy as I expected.

我曾尝试将 @Transactional 注释添加到我的方法中,但显然它仅适用于 EJB.我实际上尝试将我的 bean 转换为 EJB 而不是 CDI bean,但我仍然没有将事务处理到我的 @PostConstruct 方法.它适用于 bean 中的其他方法,但不适用于我的 @PostConstruct 初始化方法.

I have tried adding @Transactional annotation to my method, but apparently it only works with EJB. I actually tried converting my bean to EJB instead of CDI bean, but I still didn't get transaction to my @PostConstruct method. It worked with other methods in the bean, but not with my @PostConstruct initialization method.

然后我阅读了关于创建方法拦截器以获取 CDI bean 的事务:

Then I read about creating method interceptor to get transactions to CDI beans:

http://eubauer.de/kingsware/2012/01/16/cdi-and-transactions-eg-in-jboss-7-0-2/

我也试过这个,但没有运气.它也不起作用.

I tried this too, but no luck. It doesnt work either.

那么如何在 CDI bean 中将事务传递给 @PostConstruct 初始化方法?

So how does one get transactions to a @PostConstruct initialization method in a CDI bean?

推荐答案

显然是这样的:

在@PostConstruct 中(与来自 InitializingBean 接口的 afterPropertiesSet 一样)没有办法确保所有的后期处理都已经完成,所以(确实)有可以没有交易.确保其有效的唯一方法是使用交易模板.

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 the only way to do something with the database from the @PostConstruct is 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
            }
        });
   }
}

注意:类似的线程,但引用 Spring 框架 @Transactional on @PostConstruct 方法

NOTE: similar thread but referencing Spring framework @Transactional on @PostConstruct method

这篇关于如何将事务获取到@PostConstruct CDI bean 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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