What is the Difference Between EJB2 and EJB3?

🆚 Go to Comparative Table 🆚

EJB2 and EJB3 are two different versions of the Enterprise JavaBeans (EJB) specification, which is a Java API for developing enterprise applications. The key differences between EJB2 and EJB3 include:

  1. Object Orientation: EJB2 deploys entity beans for accessing databases, while EJB3 uses the Java Persistence API for data access, which is more portable and addresses issues of portability.
  2. Deployment Descriptors: EJB3 removes the need for deployment descriptors, simplifying the configuration and setup tasks. Instead, EJB3 uses annotations for deployment.
  3. Security: EJB3 supports annotation-based security, while EJB2 uses deployment descriptor-based security.
  4. POJOs: The key difference between EJB 3.0 and EJB 2.1 is that entity beans have been replaced with plain old Java objects (POJOs) now just called entities.
  5. Portability and Flexibility: EJB3 is better than EJB2 in terms of flexibility and portability. Database queries written in EJB3 are more flexible because it uses a refined EJB-QL, in place of the older version of EJB-QL, which had several limitations.
  6. Independent JVM Execution: Unlike EJB2, EJB3 can be executed in an independent Java Virtual Machine (JVM) without having to use containers.
  7. Third-Party Persistence Providers: EJB3 can be easily integrated with persistence providers offered by third parties, while EJB2 had more limited compatibility.

Overall, EJB3 offers improvements in terms of portability, flexibility, and ease of use compared to EJB2.

Comparative Table: EJB2 vs EJB3

Here is a table comparing the key differences between EJB2 and EJB3:

Feature EJB2 EJB3
Entity Bean CMR Relationships - @OneToMany
- @OneToOne
- @ManyToOne
- @ManyToMany
Simplified, uses Java Persistence API (JPA) instead of entity beans
Entity Bean Creation Create method in the home/local home interface Entity beans are Plain Old Java Objects (POJOs) and do not implement the EntityBean interface
JNDI Name Syntax jndiName = "beans.HelloBean" jndiName = "beans.HelloBean#beans.Hello"
Session Bean javax.ejb.SessionBean javax.ejb.Stateless
Control Lookup EJB 2.0 control lookup syntax requires only a reference to the JNDI name EJB 3.0 control lookup syntax requires a reference to the @SessionEJB3Control.EJBLookup(jndiName = "jndiName#businessInterface")

EJB2 and EJB3 have different approaches to managing persistence and entity bean relationships. EJB2 uses a more verbose approach with CMR (Container Managed Relationships) and implements the EntityBean interface, while EJB3 simplifies the entity beans and uses the Java Persistence API (JPA) instead. Additionally, the JNDI name syntax and session bean management have changed between the two versions.