Java判断是否在事务中,如何判断Java EE 6拦截器中的事务是否处于活动状态?

I am planning to write an interceptor for an EJB that will do basically the following:

@AroundInvoke

public Object setContext(InvocationContext ctx) throws Exception {

em.createQuery("... set something [database specific] ...").getSingleResult();

try {

return ctx.proceed();

} finally {

em.flush();

em.createQuery("... unset something [database specific] ...").getSingleResult();

}

}

The problem is that em.flush() throws an exception if it is applied to a method annotated with @TransactionAttribute(NOT_SUPPORTED) or @TransactionAttribute(SUPPORTS) (i.e. read-only methods), while it works fine with methods using the default @TransactionAttribute(REQUIRED) (i.e. methods that change the database).

Is there a way to tell whether a transaction is active in order to avoid the call to em.flush() when there is no transaction currently running, or must I create two interceptors, one with em.flush() and one without it?

I cannot inject a UserTransaction since the bean uses container-managed transactions. EntityManager's (em) transaction methods only work with resource_local transactions, not with JTA transactions. I need the em.flush() call to be sure that the unset query is the last thing that runs.

As bonus question, does anyone knows if what I am trying to do is some kind of bad practice? I know that the interceptor runs in the same context as the bean, so it will be safe to share things via the database session, but I must be really careful to unset everything on exit because connections are pooled in the container.

解决方案

You can inject a TransactionSynchronizationRegistry and use getTransactionStatus to get the status of the transaction in the current context, it returns an int which is a contant in the Status class, in your case you are looking for STATUS_NO_TRANSACTION

Inject:

@Resource

TransactionSynchronizationRegistry tsr;

Check Transaction Status:

if (Status.STATUS_NO_TRANSACTION == tsr.getTransactionStatus()) {

// no transaction

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值