Does CDI @Transactional REQUIRES_NEW works in local methods
Asked Answered
C

1

6

Does CDI @Transactional(Transactional.TxType.REQUIRES_NEW) works when is called inside the same bean:

@Transactional
public void method1() {
    for(...) {
        method2();
    }
}

@Transactional(Transactional.TxType.REQUIRES_NEW)
public void method2() {
   ...
}

I suppose it doesn't works because local calls can't be intercepted by the proxy. In that case what is the recommeded usage pattern if I want to manage each call of method2 in a new transaction. The obvious one is to create another bean, but it's something I don't like.

Counterstroke answered 21/3, 2015 at 8:15 Comment(3)
If you can use EJB for your controllers instead of CDI you will be better off at this point. EJBs are just as simple, more mature and don't have issues like not being able to self reference or call local methods. With EJB you can either inject a ref of the same bean or use the EJB session context to call the local method.Wicked
@Wicked But the issue with local methods it's the same, isn't it? The solution will be to obtain the Bussiness interface and call the local method?Counterstroke
I wonder why you actually want to open another transaction? I don't see a try/catch in your method1 What happens if one of the method2 transactions fails? Is the transaction surrounding method1 really still valid? Usually transactions give you an all-or-nothing semantics, and with your above code snippet I struggle to see the benefit of a nested transaction. FWIW, by the SRP you most probably still want to move method2 to another bean, in particular if its value/use-case even justifies a new transaction.Default
V
7

Interception of local method calls does not work for CDI and you cannot inject your class directly into itself (cyclic dependency). See also CDI call interceptor annotated method within same instance

The self injection issue is still open, see https://issues.jboss.org/browse/CDI-414

Varnado answered 21/3, 2015 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.