JEE7: Do EJB and CDI beans support container-managed transactions?

前端 未结 2 1245
小蘑菇
小蘑菇 2020-11-29 03:06

Java EE7 consists of a bunch of \"bean\" definitions:

  • Managed Beans 1.0 (JSR-316 / JSR-250)
  • Dependency Injection for Java 1.0 (JSR-330)
  • CDI 1
相关标签:
2条回答
  • 2020-11-29 03:35

    Until Java EE 7 only EJB was transactional and the @Transactional annotation didn't exist.

    Since Java EE 7 and JTA 1.2 you can use transactional interceptor in CDI with @Transactional annotation.

    To answer your question about the best type of bean to use, the answer is CDI by default.

    CDI beans are lighter than EJB and support a lot of feature (including being an EJB) and is activated by default (when you add beans.xml file to your app). Since Java EE 6 @Inject supersede @EJB. Even if you use remote EJBs (feature not existing in CDI) the best practice suggest that you @EJB once to inject remote EJB and a CDI producer to expose it as a CDI bean

    public class Resources {
    
        @EJB
        @Produces
        MyRemoteEJB ejb;
    
    }
    

    The same is suggested for Java EE resources

    public class Resources2 {
    
        @PersistenceContext
        @Produces
        EntityManager em;
    
    }
    

    These producers will be used later

    public class MyBean {
    
        @Inject
        MyRemoteEJB bean;
    
        @Inject
        EntityManager em;
    
    }
    

    EJB continue to make sense for certain services they include like JMS or Asynchronous treatment, but you'll use them as CDI bean.

    0 讨论(0)
  • 2020-11-29 03:36

    The javadoc of Transactional says:

    The javax.transaction.Transactional annotation provides the application the ability to declaratively control transaction boundaries on CDI managed beans, as well as classes defined as managed beans by the Java EE specification, at both the class and method level where method level annotations override those at the class level.

    So, your assumptions are wrong. EJBs, until Java EE 6, were the only kinds of components to support declarative transactions. The Transactional annotation has precisely been introduced in Java EE 7 to make non-EJB, managed CDI beans transactional.

    0 讨论(0)
提交回复
热议问题