Transaction management and CDI
Asked Answered
S

3

5

I would like to develop an application with CDI (I use Spring usually) to discover this technology.

I have read many articles about CDI to learn how it works. I have a simple question about transaction management (for persistence in database for example):

Is it mandatory to use EJB 3.1 to have transaction management or is it possible to have it with CDI only ?

Thanks.

Settle answered 5/1, 2013 at 14:30 Comment(1)
Transactions are out of the scope of the CDI spec. There might exist a declarative transaction framework using CDI interceptors, though.Tetrode
Q
8

No, you can do it with CDI. You simply need to create an interceptor that starts, commits or rollsback a transaction. It's really not that hard. In Java EE 7 there will be a @Transactional for all managed beans (JSF, CDI, EJB, etc) that will be a CDI interceptor.

EDIT: If you'd like to take a look at some that are already done, Apache DeltaSpike and Seam 3 (no longer being developed) have interceptors to handle transactions.

Qintar answered 6/1, 2013 at 7:38 Comment(2)
Thanks for your answer. So, do you think it's better to use ejb 3.1 (to keep standards) or create an CDI interceptor ? I don't want to use seam 3 because as you say, it's no longer developed.Settle
Honestly, it all depends on what you need. If you need some of the other features of EJB, pooling, security, etc go with EJB, otherwise create the interceptor and go with that (which is actually still standard as you're not doing anything which isn't in the platform, just some different glue)Qintar
W
2

Transaction management is a different API so it does not matter weather you use it with CDI or EJB.

Weightless answered 27/1, 2013 at 14:17 Comment(0)
U
2

By the moment (until that Java EE 7 arrives) you could mix a CDI (No more @ManagedBean) with a EJB (transactional features) just like Adam Bien shows in his post:

@Stateless
@Named("helloService")
public class HelloService {

    @EJB ClockService clockService;

    public String getHello(){
        return "Hello from EJB / CDI: " + clockService.currentTime();
    }
} 

Something good about this is that your EJB is exposed directly to the View Tier, no need of @Interceptor, but, don't abuse of this approach you could high coupling between View and Control tiers

From the JavaEE7 Spec: " Although CDI, JSF and EJB already all build on a common but very abstract concept called the managed bean, it seems that JSF Managed Beans might be dropped in favor of CDI and EJB might be retrofitted as a set of CDI services."

References:

  1. http://www.adam-bien.com/roller/abien/entry/ejb_3_1_killed_the

  2. http://jdevelopment.nl/open-source/java-ee-7-progress-page/

Usurer answered 4/5, 2013 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.