0% found this document useful (0 votes)
40 views21 pages

Advanced Java Unit-IV - 2nd Year-Econtent

Uploaded by

Dr.K.Sankar
The document provides an overview of Enterprise Java Beans (EJBs), including the types of EJBs, benefits of using EJBs, and how to set up an environment and create a simple EJB application. It discusses the three types of EJBs - session beans, entity beans, and message-driven beans. It also outlines the steps to set up a development environment, including installing a JDK, application server, and IDE. Finally, it provides a detailed guide on creating a basic EJB application with a stateless session bean and client, covering creating the projects, bean, client class, deployment, and testing.

Copyright:

© All Rights Reserved

Available Formats

Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
40 views21 pages

Advanced Java Unit-IV - 2nd Year-Econtent

Uploaded by

Dr.K.Sankar
The document provides an overview of Enterprise Java Beans (EJBs), including the types of EJBs, benefits of using EJBs, and how to set up an environment and create a simple EJB application. It discusses the three types of EJBs - session beans, entity beans, and message-driven beans. It also outlines the steps to set up a development environment, including installing a JDK, application server, and IDE. Finally, it provides a detailed guide on creating a basic EJB application with a stateless session bean and client, covering creating the projects, bean, client class, deployment, and testing.

Copyright:

© All Rights Reserved

Available Formats

Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

THE NEW COLLEGE (AUTONOMOUS), CHENNAI-14.

Department of Computer Applications – Shift – II


Subject: Advanced Java Programming Study Material Class: II BCA
----------------------------------------------------------------------------------------------------------------------------------
UNIT-IV
1. EJB OVERVIEW

EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE platform has
component based architecture to provide multi-tiered, distributed and highly transactional features to
enterprise level applications.

EJB provides an architecture to develop and deploy component based enterprise applications considering
robustness, high scalability, and high performance. An EJB application can be deployed on any of the
application server compliant with the J2EE 1.3 standard specification.

Types of EJB

EJB is primarily divided into three categories; following table lists their names with brief descriptions −

S.No Type & Description

1 Session Bean
Session bean stores data of a particular user for a single session. It can be stateful or stateless. It is less
resource intensive as compared to entity bean. Session bean gets destroyed as soon as user session
terminates.

2 Entity Bean
Entity beans represent persistent data storage. User data can be saved to database via entity beans and
later on can be retrieved from the database in the entity bean.

3 Message Driven Bean


Message driven beans are used in context of JMS (Java Messaging Service). Message Driven Beans can
consumes JMS messages from external entities and act accordingly.

Benefits
 Simplified development of large-scale enterprise level application.
 Application Server/EJB container provides most of the system level services like transaction handling,
logging, load balancing, persistence mechanism, exception handling, and so on.
 EJB container manages life cycle of EJB instances, thus developer needs not to worry about when to
create/delete EJB objects.

Prepared by Dr.K.Sankar Page 1 of 21


2. EJB - ENVIRONMENT SETUP
To work with Enterprise JavaBeans (EJB), it's crucial to set up an appropriate development environment.
This involves selecting and configuring a Java Development Kit (JDK), an EJB-compatible application
server, and an Integrated Development Environment (IDE) that supports EJB development. Let's go through
each component required for an EJB development environment.
1. Java Development Kit (JDK)
EJB development is done in Java, so the first step is to have a JDK installed on your system. Make sure it's
compatible with the version of EJB you'll be working with. As of my last update, Java EE 8 and Jakarta EE
8 are commonly used versions that require at least JDK 8. However, newer versions might require more
recent JDKs.
 Download JDK: You can download the JDK from various providers, including the official Oracle
website or adopt open JDK distributions like AdoptOpenJDK, Amazon Corretto, or others.

2. Application Server
EJBs run within a Java EE (now Jakarta EE) application server that provides the necessary infrastructure for
executing enterprise-level applications, including transaction management, security, and concurrency.
Popular choices for application servers that support EJB include:
 WildFly (Formerly JBoss): A flexible, lightweight, and powerful application server. It is open-source
and free to use.
 GlassFish: The reference implementation of Java EE and Jakarta EE. It is open-source and offers good
support for the full Java EE specifications.
 Payara Server: Derived from GlassFish, Payara is a fully-supported application server that focuses on
reliability and security in enterprise environments.
 Apache TomEE: Built upon Apache Tomcat with additional Java EE features, TomEE is a lightweight
option that is Jakarta EE compatible.

3. Integrated Development Environment (IDE)


An IDE can significantly enhance productivity by providing code completion, debugging tools, and direct
deployment options. For EJB development, consider one of the following IDEs:
 Eclipse IDE for Enterprise Java Developers: Offers comprehensive tools for Java EE development,
including support for EJBs, JPA, and more.
 IntelliJ IDEA Ultimate: Recognized for its robust support of Java EE features, including EJB, with
advanced coding assistance, and integration with application servers.
 NetBeans: Provides out-of-the-box support for developing Java EE applications, including EJBs, with a
simple and intuitive interface.

Prepared by Dr.K.Sankar Page 2 of 21


4. Configure the Development Environment
Once you have your JDK, application server, and IDE installed, the next step is to integrate them:
 Configure JDK in IDE: Ensure your IDE is configured to use the JDK version required for your EJB
development.
 Add Application Server to IDE: Most IDEs allow you to add and configure servers within the IDE,
enabling you to deploy and manage applications directly from the IDE.

5. Start Developing
With your environment set up, you're ready to start developing EJBs. Begin by creating a new Java EE
project in your IDE, ensuring that the project settings are compatible with your application server and EJB
version. Your IDE should provide templates or wizards to help create session beans, message-driven beans,
and other Java EE components.

3. EJB - CREATE APPLICATION


Creating a simple application with Enterprise JavaBeans (EJB) involves several steps, from setting up your
development environment to writing the code and deploying it to an application server. In this guide, I'll walk
you through creating a basic EJB application that includes a stateless session bean and a client accessing this
bean. We'll use an IDE like Eclipse or IntelliJ IDEA for this example, assuming you've already set up your
environment as described in previous responses.To create a simple EJB module, we will use NetBeans, "New
project" wizard. In the example given below, We will create an EJB module project named Component.

Step 1: Create a New Project


1. Open your IDE and create a new project. Depending on your IDE, you may have the option to create a
specific EJB project or a general Java EE project. If you're using Eclipse, you can select "EJB Project"
from the list of Java EE project types.
2. Specify the project name (e.g., EjbExample) and make sure to select the correct target runtime (your
configured application server) and EJB module version.

Step 2: Create a Stateless Session Bean


1. Right-click on your project and navigate to New > Other. Select "Session Bean" from the list of EJB
components.
2. Fill in the class name (e.g., GreetingBean) and package name (e.g., com.example.ejb). Make sure
"Stateless" is selected as the session bean type.
3. Click Finish. Your IDE will generate a new stateless session bean with a default method. Modify this
bean to include a simple greeting method.
For example:
package com.example.ejb;

Prepared by Dr.K.Sankar Page 3 of 21


import javax.ejb.Stateless;
@Stateless
public class GreetingBean {
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
Step 3: Create a Client to Access the Bean
There are several ways to access an EJB, depending on your environment and the type of client you're
developing (e.g., a web application, a standalone Java application). Here, we'll create a simple Java class
within the same project to invoke the bean.
For example:
1. Create a new Java class in your project (e.g., GreetingClient).
2. Inject the EJB if you're within the same application server environment or look it up via JNDI if
accessing remotely.
For simplicity, this example assumes local access:
package com.example.client;

import com.example.ejb.GreetingBean;

import javax.ejb.EJB;

public class GreetingClient {

@EJB

private static GreetingBean greetingBean;

public static void main(String[] args) {

System.out.println(greetingBean.sayHello("World"));

}
Note: For a standalone client, JNDI lookup would be necessary, and you'd typically run it outside the
application server context. This requires setting up the client's environment to include the necessary JNDI
and EJB client libraries from your application server.

Step 4: Deploy and Test the Application


 Package your application as an EAR or WAR file, depending on your project's structure and
requirements. Your IDE should provide facilities to do this, often through a "Build" or "Export" option.

Prepared by Dr.K.Sankar Page 4 of 21


 Deploy the package to your application server. This can usually be done directly from the IDE or by
using the application server's administration console.
 Run the GreetingClient class as a Java application from your IDE, or deploy and access your client
according to its nature (e.g., as a servlet, if you've created a web client).
 Verify the output. If everything is set up correctly, you should see the greeting message output to your
console or web interface.

Troubleshooting
 Ensure your EJB is properly annotated and deployed.
 Check the application server logs for deployment errors.
 Verify that the client is correctly accessing the EJB. Remote access involves additional configuration,
including specifying the correct JNDI name.
Creating an EJB application involves understanding both the EJB specifications and the specifics of your
development and runtime environment. This example provides a basic starting point, but EJB offers much
more, including entity beans for ORM, message-driven beans for asynchronous processing, and much more
sophisticated transaction and security management features.

4. EJB - STATELESS BEAN


Stateless session beans are one of the core components in Enterprise JavaBeans (EJB) for creating scalable
enterprise applications. They are designed to offer business methods to clients without any conversational
state, meaning each method invocation is independent of any previous invocation. Due to their stateless
nature, these beans can handle multiple requests from different clients, making them highly scalable and
efficient for operations where state does not need to be preserved across method calls.

Characteristics of Stateless Session Beans


 No Conversational State: They do not maintain any state information for a specific client across
method calls. Any instance variable set during a method invocation will not be retained for the next
method invocation.
 Pooling: Application servers pool stateless bean instances to handle requests from clients. This allows
efficient resource management as the container can assign any available bean instance to serve a new
request.
 Lifecycle: Has a simplified lifecycle compared to stateful session beans, mainly including creation,
business method invocation, and destruction phases.

Creating a Stateless Session Bean


The development of a stateless session bean involves defining a business interface and a bean class that
implements this interface.
Prepared by Dr.K.Sankar Page 5 of 21
Business Interface: This is a Java interface that defines the business methods the bean will expose to
clients. It can be annotated with @Local for local access (within the same application) or @Remote for
remote access (from a different application).
Example:
import javax.ejb.Local;
@Local
public interface GreetingService {
String greet(String name);
}
Bean Class
The bean class implements the business interface and is annotated with @Stateless to indicate that it is a
stateless session bean.
import javax.ejb.Stateless;
@Stateless
public class GreetingBean implements GreetingService {
@Override
public String greet(String name) {
return "Hello, " + name + "!";
}
}

Accessing a Stateless Session Bean


Stateless session beans can be accessed by clients in various ways, including injection and JNDI lookup.
Dependency Injection
Within a Java EE environment, clients can access the bean through dependency injection using the @EJB
annotation.
import javax.ejb.EJB;
public class GreetingClient {
@EJB
private GreetingService greetingService;
public void sayHello() {
System.out.println(greetingService.greet("EJB World"));
}
}

Prepared by Dr.K.Sankar Page 6 of 21


JNDI Lookup
For clients outside of the Java EE container (like in a standalone Java application), a JNDI lookup can be
used to obtain a reference to the bean.
import javax.naming.InitialContext;
public class Client {
public static void main(String[] args) throws Exception {
InitialContext ctx = new InitialContext();
GreetingService service = (GreetingService)
ctx.lookup("java:global/myApp/GreetingBean!com.example.GreetingService");
System.out.println(service.greet("JNDI World"));
}
}
Stateless session beans are essential for building scalable, high-performing enterprise applications using the
EJB specification. They enable the development of business logic that can efficiently serve multiple clients
simultaneously without the overhead of managing state between invocations.

5. EJB - STATEFUL BEAN


Stateful Session Beans in Enterprise JavaBeans (EJB) are a type of EJB designed to maintain state across
multiple method calls and transactions for a specific client. Unlike Stateless Session Beans, which do not
maintain any conversational state between method invocations, Stateful Session Beans are capable of
holding data specific to an individual client, making them suitable for tasks where client-interaction state
needs to be preserved.

Key Features of Stateful Session Beans:


1. Conversational State: Stateful beans can maintain state information (instance variables) throughout a
session, allowing for data persistence across multiple method calls from the same client.
2. Passivation and Activation: To manage system resources efficiently, the EJB container can passivate
(serialize and store) inactive stateful session beans to secondary storage. When the client accesses the
bean again, it is activated (deserialized and restored to memory), allowing the bean to continue the
conversation with its client.
3. @PrePassivate and @PostActivate: These annotations allow developers to specify methods to be
called by the container before passivation and after activation, enabling the bean to release and reacquire
resources.
4. Lifecycle: Stateful session beans have a more complex lifecycle compared to stateless session beans,
including stages for bean creation, passivation, activation, and removal.
5. @Remove Method: This annotation specifies a method that, when called, signals the container to
destroy the bean instance, ending its lifecycle and releasing resources.
Prepared by Dr.K.Sankar Page 7 of 21
Implementing a Stateful Session Bean:
To implement a Stateful Session Bean, you define a bean class that contains business methods, state
(instance variables), and any lifecycle callback methods as needed.

Example of a Stateful Session Bean:


import javax.ejb.Stateful;
@Stateful
public class ShoppingCartBean implements ShoppingCart
{
public void addItem(String item)
{
items.add(item);
}
public void removeItem(String item)
{
items.remove(item);
}
public List<String> getItems()
{
return items;
}
@Remove
public void checkout()
{
// Perform checkout operations
// Bean will be removed after this method completes
}
// Optional lifecycle callback methods
@PostConstruct
public void initialize()
{
// Initialization code
}
@PreDestroy
public void cleanup()
{
// Cleanup code before bean is destroyed
}
}

Accessing Stateful Session Beans:


Clients can access Stateful Session Beans either through dependency injection or JNDI lookup, similar to
Stateless Session Beans. However, since Stateful Beans maintain state for a specific client, each client gets
its own instance of the bean.
Prepared by Dr.K.Sankar Page 8 of 21
import javax.ejb.EJB;
public class ShoppingCartClient
{
@EJB
private ShoppingCart shoppingCart;
public void doShopping()
{
shoppingCart.addItem("Apple");
shoppingCart.addItem("Banana");
// ...
shoppingCart.checkout();
}
}
Stateful Session Beans are essential for scenarios where conversational state needs to be maintained across
multiple method invocations for a client. They are ideal for implementing workflows, session-based
interactions, and any process where state about the client's interaction needs to be preserved. However,
because they consume more resources and are more complex to manage than Stateless Session Beans, they
should be used judiciously and when genuinely required by the application logic.

6. MESSAGE DRIVEN BEANS IN EJB


Message-Driven Beans (MDBs) are an essential component of the Enterprise JavaBeans (EJB) technology
in Java EE (Enterprise Edition). They provide an efficient way to process asynchronous messages in a Java
EE application. Here's an overview of Message-Driven Beans in EJB:

1. Asynchronous Processing: Message-Driven Beans allow for asynchronous processing of messages,


which means that a component can send a message to a Message-Driven Bean and continue its work
without waiting for a response. This is particularly useful in scenarios where the processing of a message
might take a significant amount of time or where the sender and receiver of the message are not tightly
coupled.
2. Integration with Message-Oriented Middleware (MOM): Message-Driven Beans are designed to
integrate seamlessly with Message-Oriented Middleware systems like Java Message Service (JMS).
They can listen to messages from JMS destinations (queues or topics) and execute business logic based
on the received messages.
3. Lifecycle Management: Message-Driven Beans have a well-defined lifecycle managed by the EJB
container. They are instantiated by the container when a message arrives and are then ready to process
the message. After processing the message, the container can pool and reuse the Message-Driven Bean
instance for subsequent messages, thus improving performance.
4. Annotation-Based Programming Model: In modern Java EE development, Message-Driven Beans are
typically developed using annotations, which simplifies the code and reduces the need for deployment

Prepared by Dr.K.Sankar Page 9 of 21


descriptors. Annotations like @MessageDriven are used to declare a class as a Message-Driven Bean
and specify its activation configuration.
5. Concurrency Control: Message-Driven Beans can be configured to handle concurrent message
processing. Developers can specify the maximum number of instances (threads) that can concurrently
process messages, as well as the maximum number of messages that can be processed concurrently per
instance.
6. Transaction Management: Message-Driven Beans support transaction management, allowing
developers to specify whether message processing should be part of a transaction. This ensures data
consistency and reliability in distributed systems where messages might trigger database operations or
other transactional tasks.
7. Error Handling and Exception Propagation: Message-Driven Beans provide mechanisms for error
handling and exception propagation. Developers can define exception handlers to handle errors
gracefully and control the behavior of the Message-Driven Bean in case of failures during message
processing.
Overall, Message-Driven Beans play a crucial role in building robust and scalable Java EE applications,
especially in scenarios involving asynchronous communication and message-based integration.

8. EJB – PERSISTENCE
In the context of Enterprise JavaBeans (EJB), persistence refers to the capability of storing and retrieving
data from a database using the Java Persistence API (JPA). EJBs provide a powerful mechanism for
managing persistent data within Java EE applications. Here's an overview of EJB persistence:
1. Java Persistence API (JPA): JPA is a Java specification for accessing, managing, and persisting data
between Java objects and relational databases. It provides a set of standard APIs and annotations for
mapping Java objects to database tables and executing CRUD (Create, Read, Update, Delete) operations.
2. Entity Beans: In EJB, entity beans represent persistent data objects. These beans are typically annotated
with JPA annotations such as @Entity, @Table, @Id, @GeneratedValue, etc., to define their
mapping to database tables and their primary key properties.
3. Container-Managed Persistence (CMP): EJB supports container-managed persistence, where the EJB
container is responsible for managing the lifecycle and persistence of entity beans. The container handles
tasks such as transaction management, connection pooling, and caching, thus relieving developers from
low-level database operations.
4. Container-Managed EntityManager: In EJB, the EntityManager is the primary interface for working
with JPA entities. With container-managed persistence, the EntityManager is managed by the EJB
container, and developers can inject it into their EJB components using annotations like

Prepared by Dr.K.Sankar Page 10 of 21


@PersistenceContext. This allows for transparent persistence management without the need for
developers to explicitly handle database connections and transactions.
5. Transaction Management: EJB provides built-in support for declarative transaction management.
Developers can annotate EJB methods with transaction attributes (@TransactionAttribute) to specify
the desired transactional behavior. The container then automatically manages transactions, ensuring data
consistency and integrity.
6. Querying Data: EJB supports JPQL (Java Persistence Query Language), a SQL-like query language for
executing database queries against JPA entities. Developers can use JPQL to perform complex queries,
filtering, and sorting operations on persistent data.
7. Relationship Mapping: JPA allows developers to define relationships between entity beans using
annotations such as @OneToMany, @ManyToOne, @ManyToMany, etc. These annotations define
the associations between entities, enabling developers to navigate and manipulate object relationships at
the application level while maintaining referential integrity at the database level.
8. Caching: EJB containers often provide caching mechanisms to optimize the performance of persistent
data access. Entities and query results can be cached at various levels (e.g., entity-level cache, second-
level cache) to reduce database round trips and improve application performance.
Overall, EJB persistence simplifies the development of data-driven Java EE applications by providing a
high-level abstraction over database operations, transaction management, and entity relationship
management. It promotes productivity, maintainability, and scalability in enterprise application
development.

9. EJB – ANNOTATIONS
Enterprise JavaBeans (EJB) annotations provide a streamlined and declarative way to configure and
customize EJB components, reducing the reliance on verbose XML deployment descriptors. Annotations are
used to specify various aspects of EJB components, such as session beans, message-driven beans, and entity
beans. Here are some commonly used annotations in EJB:
1. @Stateless: This annotation is used to mark a class as a stateless session bean. Stateless session beans
are typically used to encapsulate business logic that doesn't require maintaining conversational state
between method invocations.
2. @Stateful: Marks a class as a stateful session bean. Stateful session beans maintain conversational state
between client invocations and are suitable for use cases where the client needs to maintain a
conversational state with the server across multiple method invocations.
3. @Singleton: Indicates that a class is a singleton session bean. Singleton session beans are instantiated
only once per application and can be accessed by multiple clients concurrently. They are often used for
caching, resource management, or other application-wide services.

Prepared by Dr.K.Sankar Page 11 of 21


4. @MessageDriven: Used to annotate a class as a message-driven bean (MDB). MDBs are used to
asynchronously process messages from a messaging system, such as Java Message Service (JMS). This
annotation is accompanied by other annotations to specify the message listener interface, destination,
and other configuration details.
5. @Local: Specifies that an EJB interface is intended for local access only, meaning that it can be invoked
by components within the same application but not by remote clients.
6. @Remote: Marks an EJB interface as remote, allowing it to be accessed by clients from different JVMs
or even from remote machines over a network.
7. @LocalBean: Used to indicate that a session bean exposes a no-interface view. With this annotation,
clients can directly invoke the methods of the session bean without needing a separate interface.
8. @PostConstruct and @PreDestroy: These annotations mark methods that should be executed after the
bean has been constructed and before it is destroyed, respectively. These methods can be used for
initialization and cleanup tasks.
9. @Schedule: Specifies that a method should be automatically invoked according to a predefined
schedule. This annotation is commonly used in singleton session beans to implement scheduled tasks.
10. @PersistenceContext: Used to inject a persistence context (EntityManager) into an EJB component.
This context allows the component to interact with the underlying database using the Java Persistence
API (JPA).
Annotations in EJB provide a convenient and flexible way to configure and customize EJB components,
making development more efficient and reducing the need for verbose XML deployment descriptors. They
promote a clearer and more concise coding style while still providing powerful capabilities for building
robust enterprise applications

10. CALL BACKS in EJB


In Enterprise JavaBeans (EJB), callbacks refer to methods within EJB components that are automatically
invoked by the EJB container in response to certain lifecycle events or business logic triggers. These
callbacks allow developers to hook into the EJB container's lifecycle management and transaction
processing, performing specific actions at key points during the execution of the EJB component. Here are
the main types of callbacks in EJB:
1. Lifecycle Callbacks:
@PostConstruct: Annotated with @PostConstruct, a method is executed by the EJB container
immediately after the EJB instance has been created and its dependencies have been injected. This callback
is commonly used for initialization tasks.
@PostConstruct
public void initialize()
{
Prepared by Dr.K.Sankar Page 12 of 21
// Initialization logic
}
@PreDestroy: Annotated with @PreDestroy, a method is executed by the EJB container just before the
EJB instance is destroyed. This callback is used for cleanup tasks.
@PreDestroy
public void cleanup()
{
// Cleanup logic
}

2. Transaction Synchronization Callbacks:


 SessionSynchronization Interface: For stateful session beans, the SessionSynchronization
interface provides methods (afterBegin, beforeCompletion, afterCompletion) that are invoked by
the EJB container to notify the bean about transaction-related events.
@Override
public void afterBegin() throws EJBException, RemoteException
{
// Transaction begin logic
}

@Override
public void beforeCompletion() throws EJBException, RemoteException
{
// Before transaction completion logic
}

@Override
public void afterCompletion(boolean committed) throws EJBException, RemoteException
{
// After transaction completion logic
}
3. Timeout Callbacks:
 @Timeout: Annotated with @Timeout, a method in stateful and singleton session beans is invoked
when a timer expires. This callback is useful for scheduling periodic or delayed tasks.
@Timeout
public void timeoutHandler(Timer timer) {
// Timer expiration logic
}
These callbacks provide a way for developers to manage the lifecycle of EJB components, integrate with
transaction processing, and handle timed events efficiently within the EJB container. By utilizing callbacks,
developers can implement logic that is automatically triggered at specific points during the execution of EJB
components, improving modularity, and reducing boilerplate code.

Prepared by Dr.K.Sankar Page 13 of 21


11. TIMER SERVICE in EJB
The Timer Service in Enterprise JavaBeans (EJB) provides a mechanism for creating and managing timed
events within the EJB container. This service allows developers to schedule tasks to be executed at specified
times, either once or repeatedly. Here's an overview of the Timer Service in EJB:
1. Purpose: The Timer Service enables developers to implement time-based functionality in EJB
components without relying on external schedulers or threading mechanisms. It's particularly useful for
tasks that need to be executed periodically or at specific intervals within the EJB container environment.
2. Types of Timers:
1. Programmatic Timers: Developers can create programmatic timers by obtaining a reference to
the Timer Service and using it to schedule timer events programmatically.
2. Automatic Timers: Automatic timers are created by annotating methods within EJB
components with the @Schedule annotation. The EJB container automatically invokes these
methods according to the specified schedule.
3. Creating Programmatic Timers:
1. To create a programmatic timer, the EJB component obtains a reference to the Timer Service
through dependency injection or JNDI lookup.
2. Once obtained, the component can use the Timer Service to schedule timers by specifying the
initial duration and optional interval.
@Stateless
public class MyTimerBean
{
@Resource
TimerService timerService;

public void scheduleTimer(long duration, long interval)


{
timerService.createTimer(duration, interval, "MyTimer");
}

@Timeout
public void timeoutHandler(Timer timer)
{
// Timer expiration logic
}
}
4. Automatic Timers with @Schedule Annotation:
 Developers can annotate methods with the @Schedule annotation to specify when the method
should be automatically invoked.

Prepared by Dr.K.Sankar Page 14 of 21


 The annotation supports various attributes to define the schedule, such as second, minute, hour,
dayOfWeek, dayOfMonth, month, and year.
@Singleton
public class AutomaticTimerBean
{
@Schedule(hour = "*", minute = "*/5", persistent = false)
public void scheduledTask()
{
// Task to be executed every 5 minutes
}
}
5. Timer Expiration and Invocation:
 When a timer expires, the EJB container invokes the method annotated with @Timeout or the
method specified during the creation of the programmatic timer.
 The container ensures that timers are invoked within the context of a transaction, providing
transactional integrity for timer-triggered operations.
6. Managing Timers:
 EJB components can query, cancel, and obtain information about existing timers using
methods provided by the Timer Service.
 Timers can be persistent or non-persistent, depending on whether they survive server restarts
or application redeployments.
7. Error Handling:
 EJB components should handle exceptions thrown during timer invocation appropriately to
ensure robustness and reliability of the application.
Overall, the Timer Service in EJB provides a convenient and standardized way to implement time-based
functionality within the EJB container, enabling developers to schedule tasks with ease and reliability.

12. EJB - JNDI BINDINGS


In Enterprise JavaBeans (EJB), JNDI (Java Naming and Directory Interface) bindings are used to associate
logical names with EJB components and other resources, allowing them to be looked up and accessed by
clients at runtime. JNDI bindings provide a way to decouple the client code from the physical location and
implementation details of EJB components, promoting modularity and flexibility in Java EE applications.
Here's how JNDI bindings work in EJB:
1. Naming Context:
 JNDI operates within a hierarchical naming context, where names are organized in a tree-like
structure. Each component or resource in the JNDI namespace is identified by a unique name
within this context.

Prepared by Dr.K.Sankar Page 15 of 21


2. Binding EJB Components:
 EJB components are typically registered with the JNDI naming service during deployment. The
EJB container associates a logical JNDI name with each EJB component, allowing clients to look
up and access the component using this name.
3. Lookup Process:
 Clients use the JNDI API to perform a lookup operation, specifying the logical JNDI name of the
desired EJB component or resource.
 The JNDI context provides the client with a reference to the actual EJB component or resource
bound to that name, enabling the client to invoke methods or access functionality.
4. Global and Local JNDI Names:
 EJB components may have both global and local JNDI names. Global JNDI names are accessible
across the entire Java EE application server, while local JNDI names are only accessible within
the same application or module.
 Clients typically use global JNDI names to access EJB components deployed in different
applications or servers, while local JNDI names are used for components within the same
application.
5. JNDI Environment Properties:
 Clients can customize the behavior of JNDI lookups by specifying environment properties such
as the initial context factory, provider URL, security credentials, etc.
 These properties are passed to the initial context during lookup and can influence the lookup
process, such as connecting to a remote naming service or authenticating the client.
6. JNDI Lookup Examples:
 Performing a JNDI lookup in Java code typically involves obtaining an initial context and then using
it to look up the desired resource by its JNDI name.
Context ctx = new InitialContext();
MyEJBInterface ejb = (MyEJBInterface) ctx.lookup("java:global/myApp/MyEJB!com.example.MyEJBInterface");
 In this example, "java:global/myApp/MyEJB" is the global JNDI name of the EJB component
implementing the MyEJBInterface.
JNDI bindings in EJB provide a flexible and standardized mechanism for locating and accessing EJB
components and other resources within Java EE applications. They enable loose coupling between clients
and components, allowing for easier deployment, scalability, and interoperability in distributed systems.

13. EJB - QUERY LANGUAGE


In Enterprise JavaBeans (EJB), the query language used for querying data from a database is typically the
Java Persistence Query Language (JPQL). JPQL is a powerful and database-independent query language

Prepared by Dr.K.Sankar Page 16 of 21


provided by the Java Persistence API (JPA). It allows developers to perform database queries using object-
oriented syntax, working with entities and their relationships rather than tables and columns. Here's an
overview of JPQL in EJB:

1. Object-Oriented Syntax: JPQL queries are expressed using a syntax similar to SQL, but they operate
on entity objects and their relationships rather than on database tables directly. This object-oriented
approach makes JPQL queries more expressive and natural for developers working with entity data
models.
2. Entity Context: JPQL queries are executed within the context of the JPA entity manager, allowing them
to interact directly with managed entity objects. This enables JPQL queries to take advantage of JPA's
persistence context, transaction management, and caching mechanisms.
3. Query Structure: JPQL queries consist of a SELECT clause, which specifies the data to be retrieved,
and optionally a FROM clause, which specifies the entity or entities to query. Additional clauses such as
WHERE, ORDER BY, GROUP BY, and HAVING can be used to further refine the query results.
4. Parameterized Queries: JPQL queries support parameterization, allowing developers to define query
parameters that are dynamically substituted at runtime. This facilitates reusable and more secure queries,
as it helps prevent SQL injection attacks and promotes query optimization.
5. Navigating Relationships: JPQL queries can navigate entity relationships using dot notation. This
allows developers to traverse associations between entities and filter query results based on related entity
attributes.
6. Aggregate Functions: JPQL supports aggregate functions such as COUNT, SUM, AVG, MIN, and
MAX, which can be used to perform calculations and aggregations on query results.
7. Subqueries: JPQL allows the use of subqueries within queries, enabling developers to compose more
complex and flexible queries by nesting queries within one another.
8. Native SQL Queries: In addition to JPQL, EJB also supports native SQL queries through the
createNativeQuery method of the EntityManager interface. Native queries allow developers to execute
SQL queries directly against the database, providing greater flexibility for scenarios where JPQL is
insufficient.
Example of a JPQL query in EJB:
TypedQuery<Customer> query = entityManager.createQuery(
"SELECT c FROM Customer c WHERE c.age > :age", Customer.class);
query.setParameter("age", 18);
List<Customer> customers = query.getResultList();
In this example, the JPQL query retrieves all customers with an age greater than 18 from the "Customer"
entity. The ":age" parameter is parameterized and set to a specific value at runtime.

Prepared by Dr.K.Sankar Page 17 of 21


14. ACCESS DATABASE in EJB
In Enterprise Java Beans (EJB), accessing databases is typically done using the Java Persistence API (JPA),
which provides a standardized way to interact with relational databases in Java EE applications. JPA
abstracts the underlying database operations and allows developers to work with entity objects and their
relationships, rather than directly dealing with SQL queries and JDBC connections. Here's how you can
access a database using EJB and JPA:

1. Entity Classes: Define entity classes that represent the tables in your database. An entity class is a plain
Java class annotated with @Entity and optionally other JPA annotations to specify the mapping between
the class and the database table.
import javax.persistence.*;
@Entity
public class Product
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and setters
}
2. Persistence Unit: Configure a persistence unit in your EJB application's persistence.xml file. This file
specifies the database connection details, JPA provider, and entity classes to be managed by JPA.

<persistence-unit name="MyPersistenceUnit" transaction-type="JTA">


<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:/jdbc/MyDataSource</jta-data-source>
<class>com.example.Product</class>
<!-- Other configuration options -->
</persistence-unit>
3. EntityManager Injection: Inject the EntityManager into your EJB components to perform database
operations. The EntityManager is a key interface in JPA that manages the persistence context and provides
methods for CRUD operations, queries, and transaction management.

import javax.persistence.*;
@Stateless

Prepared by Dr.K.Sankar Page 18 of 21


public class ProductBean
{
@PersistenceContext
private EntityManager entityManager;
public void addProduct(Product product)
{
entityManager.persist(product);
}
public Product getProductById(Long id)
{
return entityManager.find(Product.class, id);
}
// Other methods for updating, deleting, and querying products
}
4. Transactional Operations: EJB components can benefit from transaction management provided by the
EJB container. By default, methods annotated with @Stateless or @Stateful are transactional, and the
container manages transactions automatically.
5. JPA Queries: Use JPQL (Java Persistence Query Language) to execute queries against the database.
JPQL is an object-oriented query language similar to SQL but operates on entity objects and their
relationships.
TypedQuery<Product> query = entityManager.createQuery(
"SELECT p FROM Product p WHERE p.price > :price", Product.class);
query.setParameter("price", 100.0);
List<Product> expensiveProducts = query.getResultList();
6. Error Handling: Handle exceptions thrown during database operations gracefully. JPA provides
standardized exceptions like EntityNotFoundException, PersistenceException, etc., which you can
catch and handle appropriately.
By following these steps, you can effectively access and manipulate data in a relational database within your
EJB application using JPA. This approach provides a high-level abstraction over database operations,
promotes code reusability, and improves maintainability and portability of your application.

15. EJB - EXCEPTION HANDLING


Exception handling in Enterprise JavaBeans (EJB) involves managing exceptions that may occur during the
execution of EJB components and providing appropriate error handling mechanisms to handle these
exceptions gracefully. Here's how you can handle exceptions in EJB:

1. Declarative Exception Handling:


 EJB components support declarative exception handling using annotations such as
@ApplicationException and @TransactionAttribute.
Prepared by Dr.K.Sankar Page 19 of 21
 The @ApplicationException annotation allows you to define application-specific exceptions that
should be treated as application exceptions by the container. You can specify whether these
exceptions should trigger rollback of the transaction.
 The @TransactionAttribute annotation allows you to specify transaction attributes for methods,
including whether the method should be executed within a transaction and how the container should
handle exceptions.
@Stateless
public class MyBean
{
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void businessMethod() throws MyApplicationException
{
// Business logic that may throw an exception
if (errorCondition) {
throw new MyApplicationException("Error message");
}
}
}
2. Programmatic Exception Handling:
 EJB components can handle exceptions programmatically by catching and handling them within the
methods.
 You can use standard Java exception handling mechanisms such as try-catch blocks to catch
exceptions and take appropriate action.
@Stateless
public class MyBean {
public void businessMethod() {
try {
// Business logic that may throw an exception
if (errorCondition) {
throw new MyApplicationException("Error message");
}
} catch (MyApplicationException e) {
// Handle the exception
// Optionally, log the exception or perform error recovery
}
}
}
3. Logging Exceptions:
 It's important to log exceptions for troubleshooting and debugging purposes. You can use logging
frameworks like Log4j, SLF4J, or Java Util Logging to log exceptions.
 Log the exception along with relevant contextual information such as method name, parameters, and
stack trace.
Prepared by Dr.K.Sankar Page 20 of 21
4. Error Recovery and Rollback:
 Depending on the nature of the exception, you may need to perform error recovery actions such as
rolling back the transaction, retrying the operation, or notifying the user.
 Use transaction attributes (@TransactionAttribute) to specify whether an exception should trigger
a rollback of the transaction.
5. Propagation of Exceptions:
 Define and propagate custom application-specific exceptions to provide meaningful error messages
and facilitate error handling in client code.
 Consider wrapping lower-level exceptions in higher-level exceptions to provide abstraction and
encapsulation.
By implementing appropriate exception handling strategies in your EJB components, you can enhance the
robustness, reliability, and maintainability of your Java EE applications. Effective exception handling helps
prevent unexpected failures and provides a better experience for users and administrators.

----- End of Unit-IV -----

Prepared by Dr.K.Sankar Page 21 of 21

You might also like