0% found this document useful (0 votes)
7 views18 pages

Module5 EJB

The document provides an overview of Enterprise JavaBeans (EJB) and server-side component models, detailing the architecture, types of EJB components (Session Beans, Message-Driven Beans, and Entity Beans), and their lifecycle management. It emphasizes the importance of EJB in building scalable, robust, and secure distributed applications, along with the roles of EJB clients and containers. Additionally, it discusses the separation of concerns in application design, including core concerns, cross-cutting concerns, and plumbing, to enhance maintainability and efficiency.

Uploaded by

sweetysoni5504
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views18 pages

Module5 EJB

The document provides an overview of Enterprise JavaBeans (EJB) and server-side component models, detailing the architecture, types of EJB components (Session Beans, Message-Driven Beans, and Entity Beans), and their lifecycle management. It emphasizes the importance of EJB in building scalable, robust, and secure distributed applications, along with the roles of EJB clients and containers. Additionally, it discusses the separation of concerns in application design, including core concerns, cross-cutting concerns, and plumbing, to enhance maintainability and efficiency.

Uploaded by

sweetysoni5504
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE-5

EJB and Server-Side Component Models

5.1 Introduction:
Enterprise JavaBean (EJB) is a server-side component that encapsulates the business logic of an application.
• Enterprise Javabeans run in the EJB container, a runtime environment within the GlassFish Server.
• The EJB container provides system-level services, such as transactions and security, to its enterprise beans.
These services enable you to quickly build and deploy enterprise beans, which form the core of
transactional Java EE applications.
• Although Enterprise JavaBeans (EJB) is a development architecture for building highly-scalable and
robust enterprise level applications to be deployed on J2EE compliant Application Server such as JBOSS,
Web Logic etc.
EJB Server:
The EJB server contains the EJB container,
which provides the services required by the
EJB component.
EJB Container:
An EJB container is a runtime environment
that manages one or more enterprise
javabeans. The EJB container manages the
life cycles of enterprise bean objects,
coordinates distributed transactions, and Figure 2.1: EJB Architecture
implements object security.
Generally, each EJB container is provided by an EJB server and contains a set of enterprise beans that run on the
server. If we want to execute an enterprise bean it must be placed in one of the EJB container, which provides
system level services for its execution.
Enterprise beans are used in distributed applications that typically contain the business logic. The container
performs the various tasks like: Transaction Management, Security, Resource and Lifecycle management, Remote
accessibility, concurrency control.

EJB Client:
An EJB client usually provides the user-interface logic on a client machine.
 The EJB client makes calls to remote EJB components on a server and needs to know how to find the EJB
server and how to interact with the EJB components. An EJB component can act as an EJB client by
calling methods in another EJB component.
 An EJB client does not communicate directly with an EJB component.
 The container provides proxy objects that implement the components home and remote interfaces.
 The component’s remote interface defines the business methods that can be called by the client. This is
the interface where the entire business method of [Link] package is used for creating
Remote interface.
 The client calls the home interface methods to create and destroy proxies for the remote interface. This is
the interface where all business method of [Link] package is used for creating Local
interface.
EJB component implementation The Java class that runs in the server implements the bean’s business logic. The
class must implement the remote interface methods and additional methods for lifecycle management.

EJB component types


You can implement three types of EJB components, each for a different purpose:
 Session beans
 Message – Driven Beans
 Entity beans

5.2 The Problem domain/ Characteristics:


The following are all prerequisites to develop the enterprise applications with highly secured, robust and scalable
distributed applications.
 Secure  Scalable  Robust/resilient
 Sound/maintains integrity  Interoperable  Correct/functions as specified

5.3 Breaking Up Responsibilities:


For the sake of simplicity, we may categorize all code in a system into one of three flavors:
 Core concerns  Cross-cutting concerns  Plumbing

Core concerns:
The primary purpose of an application is to satisfy business logic, the set of rules that dictate its expected
behaviour.
Example: An email client must be able to let its users read, compose, send, and organize email. All functions
related to the fulfilment of business logic fall into the category of core concerns.
Object-oriented principles give themselves well toward modelling business logic. Typically done via separation
of concerns, a related set of functionality
may be compartmentalized in a module,
with well-defined interfaces for how each
component will interact (see Figure 2.1).

Figure 2.2: Module, each business case, interacting with one


another modules
Cross-cutting concerns:
While the core of an application defines its primary function, there is a host of secondary operations necessary to
keep things running correctly and efficiently.
 Security assertions, transactional
boundaries, concurrency policies—all are
helpful in ensuring the integrity of the
system is in check. We define these as
aspects.
 The problem with aspects is that they’re
basically tangential to core concerns.
 In other words, cross-cutting concerns
are intended to stretch across modules Figure 2.3: Aspects working uniformly across modules
(See Figure 2.3).

Plumbing:
Once modules have been built to address the core, there’s still the matter of getting data and invocations from
point A to point B. Plumbing provides this routing, and may take several forms:
• Forwarding control from an HTTP request to some action handler
• Obtaining a JDBC connection or JavaMail session
• Mapping a non-native request (JSON, ActionScript, RDBMS SQL) into a Java object

A sufficiently decoupled system defines interfaces for each module. This ensures that components may be
developed in isolation, limits the need for explicit dependencies, and encourages parallel development.

Plumbing code is nothing more than an


adapter between endpoints and provides
few merits of its own (Figure 2-4).

Plumbing is a means to an end, and


therefore of little value in and of itself. It
will benefit us to take an approach that
minimizes the time we spend getting
data from one endpoint to another.

Figure 2.4: Plumbing as a connector between core concerns


5.4 Code Smart, Not Hard:
It’s a likely requirement that business logic be unique to your application. A lot to consider before even a single
line of code is written. That, the more code can be done for us, the less code we have to do ourselves.
Let’s say we want to register a new user with the system using traditional object-oriented methodology, we had.
 Check that we have permission to register someone new (Security)
Module-05 EJB & Server-Side Component Models
 Start a boundary so everything is ensured to complete together, without affecting anything
else
(Transactions)
 Get a business worker delegate from some pool or cache, so we have control over
concurrency
(Performance and Transactional Isolation)
 Make a hook into the database (Resource Management)
 Store the user (Business Logic)
 Get a hook to an SMTP (mail) server (Resource Management)
 Email a confirmation (Business Logic)
 Return our worker so another call may use it (Performance and Transactional Isolation)
 Close our boundary (Transactions)

When use Enterprise Java Bean?

1. Application needs Remote Access. In other words, it is distributed. To accommodate a growing


number of users, you may need to distribute an application’s components across multiple machines.
Not only can the enterprise beans of an application run on different machines, but also their location
will remain transparent to the clients.

2. Application needs to be scalable. EJB applications supports load balancing, clustering and fail-over.

3. Application needs encapsulated business logic. EJB application is separated from


presentation and persistent layer.

5.5 Components Types/EJB:


There are 3 Types of Components Types/EJB:
1. Session Bean
2. Message-Driven Bean
3. Entity/Persistence Bean
Module-05 EJB & Server-Side Component Models

Server Side Component Types or Types of EJB

EJB are primarily of three types which are briefly described below:
i. Session Bean ii. Message Driven Bean iii. Entity Bean
 Stateless Session Bean  Point-to-Point Messaging Domain
 Statefull Session Bean  Publisher/Subscriber Messaging
 Singleton Session Bean Domain

5.6 Session Bean:


Session bean encapsulates business logic only, it can be invoked by local, remote and webservice client. It
stores data of a particular user for a single session. That can be three types:
 Stateless Session Bean  Statefull Session Bean  Singleton Session Bean
The session bean performs work for its client, shielding it from complexity by executing business tasks
inside the server. A session bean is not persistent i.e., its data is not saved to a database.
The life cycle of session bean is maintained by the application server (EJB Container).

 Stateless Session Bean:


A stateless session bean is a business object that represents business logic only. It doesn’t have state.
OR
A stateless session bean defined as conversational state between multiple method calls is not maintained
by the container.
 The stateless bean objects are pooled by the EJB container to service the request on demand. It can
be accessed by one client at a time.
 In case of concurrent access, EJB container routes each request to different instance.
 The stateless bean client may be local, remote or webservice client.

Life cycle of Stateless Session Bean


The figure 5.1 shows the life cycle of a stateless session bean. A stateless session bean has two states:
 Does Not Exist state: The bean instance is in the Does Not Exist state that means it has not been
instantiated yet.
 Method - Ready Pool state: When EJB Server is first started, several bean instances are created
and placed in the Ready pool. More instances might be created by the container as needed by the EJB
container.
Transitioning to the Method-Ready Pool
When an instance transitions from the Does Not Exist state to the Method-Ready Pool, three operations are
performed on it.
i. The bean instance is instantiated by invoking the [Link]() method on the stateless
bean class.
Module-05 EJB & Server-Side Component Models

Container decides it
needs more instances Bean Instance
in the pool to service Does Not Exist
clients

1. Create, new Instance() @PreDestroy Callback, if any


2. Dependency injection, if any
3. @PostConstructor Callback, if any
Container decides
Any client call a it does not need so
business method Method – Ready many instances in
on any bean’s the pool anymore.
Pool
business interface

Figure 5.1: Life cycle of Stateless session bean


ii. The container injects any resources that the bean’s metadata has requested via Dependency injection
annotation or XML descriptor.
iii. Then, EJB Container will call a @PostConstruct or ejbCreate() method with no-arguments.
The ejbCreate() method is invoked only once in the life cycle. Now the bean is instantiated and it
is Method –Ready Pool state.
Once an instance is in the Method-Ready Pool, it is ready to service client requests. When a client invokes a
business logic method on an EJB object, the method call through any available instance in the Method-
Ready Pool. While the instance is executing the request, it is unavailable for use by other EJB objects.
Finally, The EJB container calls @PreDestory of ejbRemove() method should close any open
resources before the stateless session bean is evicted from memory at the end of its life cycle. Now bean is
ready for garbage collection.
Example: Lab11 Program

 Stateful Session Bean:


A Stateful Session bean is a business object that represents business logic like stateless session bean.
But, it maintains state (data).
OR
A Stateful session bean defined as conversational state between multiple method calls is maintained by
the container.
Stateful session beans are dedicated to one client for their entire lives, so swapping or pooling of instances
isn’t possible
Life Cycle of a Stateful Session Bean:
The figure 5.2 shows the life cycle of a stateful session bean. It has the following states:
 Does Not Exist: The bean instance is in the Does Not Exist state that means it has not been
instantiated yet.
 Method-Ready Pool state: In the Method - Ready Pool stage, a bean instance get created and it is in
the memory of the EJB container and it is ready to serve client.
Module-05 EJB & Server-Side Component Models
When Client Calls create()method on the Home Interface, server creates new instance of the bean
and sets the SessionContext and then container calls the @PostConstructor() or
ejbCreate(args) method on the bean and places the bean into Method Ready Pool stage.
ejbRemove or Timeout moves the bean into Does Not Exist stage.

Bean Instance TimeOut


Does Not Exist

4. Create, new Instance()


@PreDestroy Callback, if any TimeOut
5. Dependency injection, if any
6. @PostConstructor Callback, if any

Client call a @PrePassivate()


business method Method – Ready
on bean’s Passive State
Pool @PostActivate()
business interface
Figure 5.3: Life cycle of Stateful session bean
 Passive state: In the Passive state the bean is passivated to conserve the resource.
 The @PrePassivate() method is called before the instance enters the "passive" state. The
instance should release any resources that it can re-acquire later in the ejbActivate()
method.
 After the passivate method completes, the instance must be in a state that allows the container
to use the Java Serialization protocol to externalize and store away the instance's state.
ejbRemove() or Timeout moves the bean into Does Not Exist stage.

 Singleton Session Bean:


Singleton Session Beans are business objects having a global shared state within a JVM.

A Singleton session bean is intended to be shared and supports concurrent access by clients. Concurrent
access to the one and only bean instance can be controlled by the container (Container-managed
concurrency, CMC) or by the bean itself (Bean-managed concurrency, BMC).

Like a stateless session bean, a singleton session bean is never passivated and has only two stages, Does Not
Exist and Method-Ready Pool for the invocation of business methods.

Life Cycle of a Singleton Session Bean:


 A singleton session bean instance’s life starts when the container invokes the newInstance
method on the session bean class to create the singleton bean instance.
 Next, the container performs any dependency injection as specified by the metadata annotations
on the bean class or by the deployment descriptor.
 The container then calls the @PostConstruct lifecycle callback interceptor methods for the bean,
if any.
 The singleton bean instance is now ready to be delegated a business method call from any client or a
call from the container to a timeout callback method.
Module-05 EJB & Server-Side Component Models

Bean Instance
Does Not Exist

7. Create, new Instance()


8. Dependency injection, if any @PreDestroy Callback, if any
9. @PostConstructor Callback, if any

TimeOut
Client call a
business method Method – Ready
on bean’s Pool
business interface

Figure 7.7: Life cycle of Singleton session bean

 The singleton bean instance is now ready to be delegated a business method call from any client or a
call from the container to a timeout callback method.
 When the application is shutting down, the container invokes the @PreDestroy lifecycle callback
interceptor methods on the singleton, if any. This ends the life of the singleton session bean instance.

5.7 Message Driven Beans:


A message driven bean (MDB) is a bean that contains business logic. But, it is invoked by passing the
message. So, it is like JMS Receiver.
MDB asynchronously receives the message and processes it. A message driven bean receives message from
queue or topic, so you must have the knowledge of JMS API.
Note: A message driven bean is like stateless session bean that encapsulates the business logic and doesn't
maintain state.

Figure 5.4: MDB architecture

About JMS API:


JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It
provides loosely coupled, reliable and asynchronous communication. JMS is also known as a messaging
service.
Understanding Messaging:
Messaging is a technique to communicate applications or software components. JMS is mainly used to send
and receive message from one application to another.
Module-05 EJB & Server-Side Component Models
JMS Programming Model:

Requirement of JMS:
Generally, user sends message to
application. But, if we want to send
message from one application to
another, we need to use JMS API.
Example: One application A is
running in INDIA and another
application B is running in USA. To
send message from A application to
B, we need to use JMS.

Figure 5.5: JMS Programming model

Advantage of JMS:
 Asynchronous: To receive the message, client is not required to send request. Message will arrive
automatically to the client.
 Reliable: It provides assurance that message is delivered.

Messaging Domains:
There are two types of messaging domains in JMS.
1. Point-to-Point Messaging Domain 2. Publisher/Subscriber Messaging Domain

1. Point-to-Point (PTP) Messaging Domain:


In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message
oriented middleware (MOM). The Queue is responsible to hold the message until receiver is ready.
In PTP model, there is no timing
dependency between sender and
receiver.

Figure 5.6: PTP architecture


2. Publisher/Subscriber (Pub/Sub) Messaging Domain: I
In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting. Here, Topic is
used as a message oriented middleware that is responsible to hold and deliver messages.
In PTP model, there is timing dependency between publisher and subscriber.
Module-05 EJB & Server-Side Component Models

Figure 5.7: PTS architecture

Life Cycle for the MDB is same as stateless session bean


Example: Lab 12 Program

5.8 Entity Bean:


Entity bean represents the persistent data stored in the database. It is a server-side component.
Following are the key actors in persistence API
 Entity - A persistent object representing the data-store record. It is good to be serializable.
 EntityManager - Persistence interface to do data operations like add/delete/update/find on persistent
object(entity). It also helps to execute queries using Query interface.
 Persistence unit ([Link]) - Persistence unit describes the properties of persistence
mechanism.
 Data Source (*[Link]) - Data Source describes the data-store related properties like connection url.
username, password etc.

Life Cycle of Entity Bean:


Figure 5.8 shows the stages that an entity bean passes through during its lifetime. After the EJB container
creates the instance, it calls the setEntityContext method of the entity bean class. The
setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While in the pooled stage, the
instance is not associated with any particular EJB object identity. All instances in the pool are identical. The
EJB container assigns an identity to an instance when moving it to the ready stage.
There are two paths from the pooled stage to the ready stage.
i. On the first path, the client invokes the create method, causing the EJB container to call the
ejbCreate and ejbPostCreate methods.
i. On the second path, the EJB container invokes the ejbActivate method. While in the ready stage,
an entity bean's business methods may be invoked.
There are also two paths from the ready stage to the pooled stage.
ii. First, a client may invoke the remove method, which causes the EJB container to call the
ejbRemove method.
iii. Second, the EJB container may invoke the ejbPassivate method.
Module-05 EJB & Server-Side Component Models

At the end of the life cycle, the EJB container


removes the instance from the pool and
invokes the unsetEntityContext
method.

In the pooled state, the values of the instance


variables are not needed. You can make these
instance variables eligible for garbage
collection by setting them to null in the
ejbPasssivate method.

Example: Lab13 Program

Figure 5.7: Life Cycle of an Entity Bean


5.9 Container Services:
In the case of EJB, the Component Model defines our interchangeable parts, and the container services are
specialists that perform the work upon them. The specification provides.

 Dependency Injection  Transactions  Naming and Object stores


 Concurrency  Security  Introperability
 Instance Pooling/caching  Timers  Lifecycle Callbacks

5.9.1 Dependency Injection:


EJB 3.0 specification provides annotations which can be applied on fields or setter methods to inject
dependencies. EJB Container uses the global JNDI registry to locate the dependency.
Following annotations are used in EJB 3.0 for dependency injection.
 @EJB - used to inject other EJB reference.
 @Resource - used to inject datasource or singleton services like sessionContext, timerService etc.

5.9.2 Concurrency:
 Assuming each Service is represented by one instance, dependency injection alone is a fine
solution for a single-threaded application; only one client may be accessing a resource at a given
time.
 However, this quickly becomes a problem in situations where a centralized server is fit to serve many
simultaneous requests.
Module-05 EJB & Server-Side Component Models
 Deadlocks and race conditions are some of the possible nightmares arising out of an environment in
which threads may compete for shared resources.
 These are hard to anticipate, harder to debug, and are prone to first exposing themselves in
production.
 Proper solutions lie outside the scope of this topic, and for good reason: EJB allows the application
developer to sidestep the problem entirely thanks to a series of concurrency policies.

5.9.3Instance
Pooling:
Because of the strict concurrency rules
enforced by the Container, an intentional
bottleneck is often introduced where a
service instance may not be available for
processing until some other request has
completed. If the service was restricted to a
singular instance, all subsequent requests
would have to queue up until their turn was
Figure 5.8: Client requests queuing for service
reached (see Figure 5.8).
Conversely, if the service was permitted to use any number of underlying instances, there would be no
guard to say how many requests could be
processed in tandem, and access across the
physical machine could crawl to a halt as its
resources were spread too thin (Figure 5-9).

Figure 5.9: Many invocations executing concurrently


with no queuing policy

EJB addresses this problem through a


technique called instance pooling, in
which each module is allocated some
number of instances with which to serve
incoming requests (Figure 5.10).
Figure 5.10: A hybrid approach using a Pool
5.9.4
Transaction:
When a bean calls createTimer(), the operation is performed in the scope of the current transaction. If
the transaction rolls back, the timer is undone and it’s not created.
In most cases, the timeout callback method on beans should have a transaction attribute of RequiresNew.
This ensures that the work performed by the callback method is in the scope of container-initiated
transactions. All that required to understand of the ACID fundamentals:
Module-05 EJB & Server-Side Component Models
 Atomicity: Every instruction in a call completes or none do. If there’s a failure halfway through,
state is restored to the point before the request was made.
 Consistency: The system will be consistent with its governing rules both before and after the
request.
 Isolation: Transactions in progress are not seen outside the scope of their request until successful
completion.
 Durability: Once a transaction successfully returns, it must commit to its changes.

5.9.5 Security:
Security is a major concern of any enterprise level application. It includes identification of user(s) or system
accessing the application and allowing or denying the access to resources within the application.
In EJB, security can be declared in declarative way called declarative security in which EJB container
manages the security concerns or Custom code can be done in EJB to handle security concern by self.

Important Terms of Security


 Authentication - This is the process ensuring that user accessing the system or application is verified
to be authentic.
 Authorization - This is the process
ensuring that authentic user has right
level of authority to access system
resources.
 User - User represents the client or
system accessing the application.
 User Groups - Users may be part of
group having certain authorities for
example administrator's group.
 User Roles - Roles defines the level of
authority a user have or permissions to
access a system resource. Figure 5.11: EJB security permitting access based
Container Managed Security
EJB 3.0 has specified following attributes/annotations of security which EJB containers implement.
 DeclareRoles - Indicates that class will accept those declared roles. Annotations are applied at class
level.
 RolesAllowed - Indicates that a method can be accessed by user of role specified. Can be applied at
class level resulting which all methods of class can be accessed buy user of role specified.
 PermitAll - Indicates that business method is accessible to all. Can be applied at class as well as at
method level.
 DenyAll - Indicates that business method is not accessible to any of user specified at class or at
method level.
Module-05 EJB & Server-Side Component Models
5.9.6
Timer
Timer Service is a mechanism using which scheduled application can be build.
Example: salary slip generation on 1st of every month. EJB 3.0 specification has specified @Timeout
annotation which helps in programming the ejb service in a stateless or message driven bean. EJB Container
calls the method which is annotated by @Timeout.

EJB Timer Service is a service provided by EJB container which helps to create timer and to schedule
callback when timer expires.

Steps to create Timer: @Stateless


Inject SessionContext in bean using public class TimerSessionBean {
@Resource annotation @Resource
private SessionContext context;
...
}

Use SessionContext object to get TimerService and to create timer. Pass time in milliseconds and message.

public void createTimer(long duration) {


[Link]().createTimer(duration, "Hello world!");
}

Steps to Use Timer:


Use @Timeout annotation to a method. Return type should be void and pass a parameter of type Timer. We
are canceling the timer after first execution otherwise it will keep running after fix intervals.

@Timeout
public void timeOutHandler(Timer timer){
[Link]("timeoutHandler : " + [Link]());
[Link]();
}

5.9.7 Naming and Object


Stores:
All naming services essentially do the same thing: they provide clients with a mechanism for locating
distributed objects or resources.
To accomplish this, a naming service must fulfill two requirements: object binding and a lookup API.

 Object binding is the association of a distributed object with a natural language name or identifier.
 A lookup API provides the client with an interface to the naming system; it simply allows us to
connect with a distributed service and request a remote reference to a specific object.
There are many different kinds of directory and naming services, and EJB vendors can choose the one that
best meets their needs, but all vendors must support the CORBA naming service in addition to any other
directory services they choose to support. Naming is a subset of the resource management features offered
by EJB.
Module-05 EJB & Server-Side Component Models
5.9.8
Interoperability:
Although it’s nice that the dependency injection facilities allow components within EJB to play nicely, we
don’t live in a bubble.
Our application may want to consume data from or provide services to other programs, perhaps written in
different implementation languages. There are a variety of open standards that address this inter-process
communication, and EJB leverages these.
Interoperability is a vital part of EJB. The specification includes the required support for Java RMI-IIOP
for remote method invocation and provides for transaction, naming, and security interoperability.

EJB also requires support for JAX-WS, JAX-RPC, Web Services for Java EE, and Web Services Metadata
for the Java Platform specifications (EJB 3.1 Specification, 2.6).

5.9.9 Lifecycle
Callbacks
Some services require some initialization or cleanup to be used properly.
Example: a file transfer module may want to open a connection to a remote server before processing requests
to transfer files and should safely release all resources before being brought out of service.
For component types that have a lifecycle, EJB allows for callback notifications, which act as a hook for the
bean provider to receive these events. In the case of our file transfer bean, this may look like:

Prototype FileTransferService{
@StartLifeCycleCallback
Function openConnection(){ . . . }

@StopLifeCycleCallback
Function openConnection(){ . . . }
}

Here we’ve annotated functions to open and close connections as callbacks; they’ll be invoked by the
container as their corresponding lifecycle states are reached.

5.9.10 Interceptors
 While it’s really nice that EJB provides aspectized handling of many of the container services, the
specification cannot possibly identify all cross-cutting concerns facing your project.
 For this reason, EJB makes it possible to define custom interceptors upon business methods and
lifecycle callbacks. This makes it easy to contain some common code in a centralized location and
have it applied to the invocation chain without impacting your core logic.

5.9.11 Platform Integration
 As a key technology within the Java Enterprise Edition (JEE) 6, EJB aggregates many of the other
platform frameworks and APIs:
 Java Transaction Service
 Java Persistence API
 Java Naming and Directory Interface (JNDI)
Module-05 EJB & Server-Side Component Models
 Security Services
 Web Services

5.10 Developing your first EJB


 Developing an EJB involves most of the same steps and concepts that you have become familiar with
when developing plain old Java objects (POJOs), with a few minor differences. The following steps
illustrate the typical process to develop and deploy an EJB:
1. Write the classes and interfaces for your enterprise bean
2. Write a deployment descriptor
3. Package the enterprise bean and associated files inside of a jar file
4. Deploy the bean
5.11 EJB and Persistence:
5.11.1 Persistence Entity Manager
 Entity bean represents the persistent data stored in the database. It is a server-side component.
 Following are the key actors in persistence API –
o Entity − A persistent object representing the data-store record. It is good to be serializable.
o EntityManager − Persistence interface to do data operations like add/delete/update/find on
persistent object(entity). It also helps to execute queries using Query interface.
o Persistence unit ([Link]) − Persistence unit describes the properties of persistence
mechanism.
o Data Source (*[Link]) − Data Source describes the data-store related properties like connection
url. user-name,password etc.

5.11.2 Mapping Persistence


The Programming model
 Entities are plain Java classes in Java Persistence.
 declare and allocate these bean classes just as you would any other plain Java object.
 interact with the entity manager service to persist, update, remove, locate, and query for entity beans.
 The entity manager service is responsible for automatically managing the entity beans’ state.
 This service takes care of enrolling the entity bean in transactions and persisting its state to the database.

The Employee Entity


The Employee class is a simple entity bean that models the concept of an employee within a
company. Java Persistence is all about relational databases.

The Bean Class


The Employee bean class is a plain Java object that you map to your relational database. It has
fields that hold state and, optionally, it has getter and setter methods to access this state.

XML Mapping File


If you do not want to use annotations to identify and map your entity beans, you can alternatively
use an XML mapping file to declare this metadata.
Module-05 EJB & Server-Side Component Models
5.12 Entity Relationship
In order to model real-world business concepts, entity beans must be capable of forming relationships.

The Seven Relationship Types

 Seven types of relationships can exist between entity beans.


 There are four types of cardinality: one-to-one, one-to-many, many-to-one, and many-to-many.
o One-to-one unidirectional
 The relationship between an employee and an address. You clearly want to be able to look
up an employee’s address, but you probably don’t care about looking up an address’s
employee.
o One-to-one bidirectional
 The relationship between an employee and a computer. Given an employee, we’ll need to
be able to look up the computer ID for tracing purposes. Assuming the computer is in the
tech department for servicing, it’s also helpful to locate the employee when all work is
completed.
o One-to-many unidirectional
 The relationship between an employee and a phone number. An employee can have many
phone numbers (business, home, cell, etc.). You might need to look up an employee’s
phone number, but you probably wouldn’t use one of those numbers to look up the
employee.
o Many-to-one unidirectional
 The relationship between an employee (manager) and direct reports. Given a manager,
we’d like to know who’s working under him or her. Similarly, we’d like to be able to find
the manager for a given employee. (Note that a many-to-one bidirectional relationship is
just another perspective on the same concept.)
o one-to-many bidirectional
 The relationship between a customer and his or her primary employee contact. Given a
customer, we’d like to know who’s in charge of handling the account. It might be less
useful to look up all the accounts a specific employee is fronting, although if you want
this capability you can implement a many-to-one bidirectional relationship.
o Many-to-many bidirectional
 The relationship between employees and tasks to be completed. Each task may be
assigned to a number of employees, and employees may be responsible for many tasks.
For now we’ll assume that given a task we need to find its related employees, but not the
other way around. (If you think you need to do so, implement it as a bidirectional
relationship.)
o Many-to many unidirectional
 The relationship between an employee and the teams to which he or she belongs. Teams
may also have many employees, and we’d like to do lookups in both directions.
Module-05 EJB & Server-Side Component Models

Questions
SN Marks
1. What are the different types of enterprise java beans? Explain. 10
2. Read each types of EJB.
Design an EJB application that demonstrate working of Session Bean with appropriate
3. 10
business logic.
Design an EJB application that demonstrate working of MessageDriven Bean with
4. 10
appropriate business logic.
Design an EJB application that demonstrate working of Persistence Bean with appropriate
5. 10
business logic.
6. Read all types of Session Bean , Message Driven Bean, Entity Bean life cycle. 10
Write a brief note on the following:
i. Instance pooling/caching
ii. Transactions
7.
iii. Security
iv. Timers
v. @Dependency Injection

You might also like