Enterprise JavaBeans (EJB) Architecture Explained: Bean Types, Container Services and a Transaction Walkthrough

See where the EJB container sits, how each bean type behaves, and what the database and message queue retain when a booking transaction commits or rolls back.

KnowledgeGate Team

Exam prep & CS education

Updated 21 Nov 20265 min read
Enterprise JavaBeans (EJB) Architecture Explained: Bean Types, Container Services and a Transaction Walkthrough

EJB is often memorised as a list of bean types, leaving the crucial boundary between client code, the container, the bean and external resources vague. The reserve("B-204", "LAB-3", 3) example traces a stateless bean, transaction T-501, a database row and a message-driven bean through commit and rollback, making each responsibility visible.

EJB architecture: the container sits between the client and the bean

EJB historically means Enterprise JavaBeans. The current official name is Jakarta Enterprise Beans, and version 4.0 uses the jakarta.ejb namespace. Older notes may use javax.ejb or EJB. The Java hub places that naming change in the wider language ecosystem.

A web, REST or application client calls a local, remote or no-interface view. The container intercepts the call and invokes a session bean, with persistence, messaging and other resources behind it. The client uses that view instead of constructing a managed bean with new.

The Jakarta Enterprise Beans 4.0 core specification assigns business methods to the bean provider and lifecycle, injection, transaction boundaries, security checks, resource management, concurrency control and interception to the container.

EJB container connects a client, bean, database row and message queue in a reservation flow.

Choose among stateless, stateful, singleton and message-driven beans

Bean kind

State or access model

Container behaviour

Suitable use

@Stateless

No conversational state between calls; any pooled instance may serve any client

Selects a ready instance

BookingService

@Stateful

Conversational field state retained for one client across calls

Client-associated lifecycle, with optional passivation and activation

Multi-step booking draft

@Singleton

One shared instance per application per JVM, with concurrent access

Application-lifetime instance plus concurrency control

Shared configuration snapshot

@MessageDriven

Asynchronous listener hidden behind a destination or endpoint

Equivalent instances can process messages concurrently

Confirmation event consumer

Classic-exam note: Older EJB models describe entity beans as persistent business data components. This legacy model is not a Jakarta Persistence entity. Enterprise Beans 4.0 places the EJB 2.x entity-bean contracts in its optional-features specification.

Quick rule: no client memory means stateless; private conversation, stateful; application-wide instance, singleton; queued work, message-driven.

Worked success path: reserve three seats inside transaction T-501

Room LAB-3 starts with availableSeats = 12, and booking B-204 does not exist. A COORDINATOR calls reserve("B-204", "LAB-3", 3) without an incoming transaction.

@Stateless BookingBean exposes a local BookingService view. Its reserve method has @TransactionAttribute(REQUIRED). The container:

  1. Authenticate the caller and allow the COORDINATOR role.

  2. Select a ready stateless instance.

  3. Start T-501, because no client transaction exists.

  4. Inject or expose the persistence and messaging resources.

  5. Invoke the business method.

The method validates 3 > 0 and 12 >= 3, computes 12 - 3 = 9, updates the seat row and inserts {id: B-204, room: LAB-3, seats: 3}. Through an injected Jakarta Messaging context enlisted in T-501, it sends BookingConfirmed{bookingId=B-204, seats=3}. The database writes and message send remain tentative until the container commits T-501.

After commit, @MessageDriven ConfirmationBean receives the event asynchronously and records one confirmation attempt in this scenario. This does not promise exact order or exactly-once delivery. Multiple instances may process concurrently, and messages may arrive out of sequence.

REQUIRED joins an existing transaction or starts one when none exists, as here. It is also the container-managed default, but the annotation keeps this example explicit.

Worked rollback path: the provisional 9 must return to 12

Reset the state: LAB-3 availableSeats = 12, no B-204, and no committed confirmation event. The same call starts T-502, provisionally changes 12 to 9, inserts the booking and sends the event through the same enlisted messaging context. Before commit, RoomClosedException("LAB-3 unavailable") occurs. The method calls EJBContext.setRollbackOnly() before the failure leaves the business path.

Rollback restores the observable state: seats are 12, booking B-204 is absent, and no staged confirmation is committed for consumption. The partial result availableSeats = 9 with no booking is incorrect.

Under container-managed demarcation, bean code must not call JDBC commit, setAutoCommit or rollback. It can mark the active transaction for rollback through setRollbackOnly(), while the container performs the actual rollback.

Two aligned transaction timelines compare success committing database seats at 9 with BookingConfirmed visible and failure rolling back to 12 with B-204 absent.

Stateful is client conversation, not merely an object with a field

Assume add returns the updated total. Ria obtains one stateful DraftBookingBean with selectedSeats = 0. Her call add("LAB-3", 2) returns 2; add("LAB-5", 1) returns 3; total() returns 3. Kabir has a separate conversation starting at 0, so his add("LAB-3", 1) returns 1. The output sequence is 2, 3, 3, 1.

That reasoning is invalid for a stateless bean. Any ready pooled instance may serve a call, so a later call is not entitled to see an earlier client's instance field. A stateful bean instead retains conversational state for its associated client.

An idle, passivation-capable stateful instance may be passivated and activated while preserving eligible conversational state. Passivation is not database persistence, and a stateful bean may declare itself non-passivation-capable. Stateless beans are not passivated. Compare this lifecycle with ordinary object identity in Object Oriented Technology Explained.

Client views and container services: identify who owns each concern

Bean code owns

Container or platform infrastructure owns

Validate requested seats

Select an instance

Calculate 12 - 3

Apply the COORDINATOR role check

Create B-204

Start or join T-501

Decide which event to send

Inject resources

Commit or roll back

Control concurrent access and deliver lifecycle callbacks

A local view supports same-application calls. A remote view supports location-independent calls with remote semantics. A no-interface view exposes local business methods through the bean class. A container-provided reference is not proof that the client holds the raw instance.

@Stateless, @Stateful, @Singleton, @MessageDriven and @TransactionAttribute declare intent; the container does the runtime work.

Legacy note: Home and component interfaces belong to the classic model. They do not justify constructing a bean directly.

How exams and interviews can test EJB architecture

Questions commonly ask you to identify conversational state, asynchronous processing, classic entity beans, container services, client views and separate client counters. Map each clue to its state owner and call style before choosing an answer.

Repair these six common traps:

Trap

Repair

Stateless means one new instance per request

The container may pool instances

Stateful means durable database state

It means client conversational state

Message-driven means a synchronous client method call

The client addresses a destination or endpoint

Singleton means one instance across every JVM

The guarantee is per application per JVM

new BookingBean() gives full EJB behaviour

It bypasses the managed reference

Entity bean equals every modern persistence entity

Classic entity beans and Jakarta Persistence entities are different models

In 30 seconds, underline state, client, shared, asynchronous, persistent and container. Draw client -> view -> container -> bean -> resource, assign ownership, then choose. For wider practice, use Coding & DSA Courses for Placements.

Short version and the next study step

The client sees a managed view, and the container wraps calls with runtime services. Session beans run synchronous business logic using stateless, stateful or singleton state models; message-driven beans consume asynchronous work. T-501 commits 12 - 3 = 9 plus B-204. T-502 rolls back to 12, with no booking or committed message. Continue with the Complete Java Course for foundations or Java Course: Concepts, MCQs and Coding Questions for structured practice, then redraw both transaction lanes from memory.