0% found this document useful (0 votes)
5 views

UNIT 4

The document provides an overview of Enterprise JavaBeans (EJB), a framework for building scalable and transactional enterprise applications within Java EE. It details key features, types of EJB, advantages, environment setup, and practical examples, including the implementation of stateless and stateful session beans in an online banking system. Additionally, it covers EJB persistence, annotations, and lifecycle callbacks to enhance development efficiency and manage system-level concerns.

Uploaded by

rjfdfn8rjd
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)
5 views

UNIT 4

The document provides an overview of Enterprise JavaBeans (EJB), a framework for building scalable and transactional enterprise applications within Java EE. It details key features, types of EJB, advantages, environment setup, and practical examples, including the implementation of stateless and stateful session beans in an online banking system. Additionally, it covers EJB persistence, annotations, and lifecycle callbacks to enhance development efficiency and manage system-level concerns.

Uploaded by

rjfdfn8rjd
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
You are on page 1/ 14

THE NEW COLLEGE (AUTONOMOUS), CHENNAI-14.

Department of Computer Applications – Shift – II


Subject: Advanced Java Programming Study Material Class: II BCA
----------------------------------------------------------------------------------------------------------------------------------
UNIT-IV

1. ENTERPRISE JAVABEANS (EJB) OVERVIEW


Enterprise JavaBeans (EJB) is a Java-based framework used for building scalable, distributed, and transactional
enterprise applications. It is a part of Java EE (Jakarta EE) and provides a way to develop server-side components
that can handle complex business logic while abstracting lower-level concerns such as transaction management,
security, and concurrency.

1.1. Key Features of EJB


1. Component-Based Architecture
o EJB allows developers to create reusable business logic components.
2. Scalability and Distributed Computing
o EJB components can be distributed across multiple servers, allowing applications to scale effectively.
3. Transaction Management
o Built-in support for handling transactions (e.g., ACID properties, automatic rollback).
4. Security and Role-Based Access Control
o Uses declarative security to restrict access to business logic.
5. Lifecycle Management
o The EJB container manages object lifecycle, including creation, pooling, and destruction.
6. Integration with Other Java EE Technologies
o Works seamlessly with technologies like JPA, JMS, JAX-RS, and Servlets.

1.2. Types of EJB


1. Session Beans (Handles business logic)
o Stateless Session Beans: Do not maintain client state. Best for handling independent requests.
o Stateful Session Beans: Maintain conversational state between method calls.
o Singleton Session Beans: One instance per application, used for shared resources.
2. Message-Driven Beans (MDBs) (Asynchronous Processing)
o Used for handling messages from JMS (Java Messaging Service).
3. Entity Beans (Deprecated)
o Previously used for database interactions (now replaced by JPA).

1.3. Advantages of EJB


Simplifies development: Developers focus on business logic while the EJB container manages system-level concerns.
Built-in transaction and security management: Reduces boilerplate code.
High scalability: Supports distributed and clustered environments.
Support for asynchronous processing: Through Message-Driven Beans (MDBs).

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.

Prepared by Dr.K.Sankar Page 1 of 14


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.

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. CREATING APPLICATION
3.1. Enterprise JavaBeans (EJB) With Real-Time Example

Prepared by Dr.K.Sankar Page 2 of 14


Enterprise JavaBeans (EJB) is a Java EE (Jakarta EE) framework for building scalable, transactional, and secure
enterprise applications. It simplifies the development of business logic by handling system-level concerns like
transactions, security, concurrency, and lifecycle management.

Real-Time Example: Online Banking System


Imagine an Online Banking System that allows users to:
1. Check account balance
2. Transfer money
3. Receive transaction notifications

EJB helps implement these features efficiently by using:


 Stateless Session Bean for balance inquiry
 Stateful Session Bean for money transfer (tracking session state)
 Message-Driven Bean (MDB) for sending notifications

3.1. STATELESS SESSION BEAN – ACCOUNT BALANCE INQUIRY


Why Stateless?
 No session tracking is needed
 Handles multiple user requests efficiently
import javax.ejb.Stateless;
@Stateless
public class AccountServiceBean {
public double getBalance(String accountNumber) {
// Simulated database lookup
return 5000.00;
}
}

Calling the EJB in a Servlet


import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/CheckBalance")
public class AccountServlet extends HttpServlet {
@EJB
private AccountServiceBean accountService;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String accountNumber = request.getParameter("accNo");
double balance = accountService.getBalance(accountNumber);
response.getWriter().println("Account Balance: $" + balance);
}
}

Prepared by Dr.K.Sankar Page 3 of 14


3.2. STATEFUL SESSION BEAN – MONEY TRANSFER
For a money transfer process, we need to maintain the transaction state (from initiation to completion).
Why Stateful?
 Keeps track of balance during the transaction
 Ensures the transaction is completed successfully

import javax.ejb.Stateful;
@Stateful
public class MoneyTransferBean {
private double balance = 5000.00; // Simulated balance
public boolean transfer(String fromAcc, String toAcc, double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Transferred $" + amount + " from " + fromAcc + " to " + toAcc);
return true;
}
return false;
}

public double getRemainingBalance() {


return balance;
}
}

Calling the EJB in a Servlet


@WebServlet("/TransferMoney")
public class TransferServlet extends HttpServlet {
@EJB
private MoneyTransferBean moneyTransfer;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fromAccount = request.getParameter("from");
String toAccount = request.getParameter("to");
double amount = Double.parseDouble(request.getParameter("amount"));

boolean success = moneyTransfer.transfer(fromAccount, toAccount, amount);


response.getWriter().println(success ? "Transfer Successful”: "Insufficient Funds");
response.getWriter().println("Remaining Balance: $" + moneyTransfer.getRemainingBalance());
}
}

3. 3. MESSAGE-DRIVEN BEAN (MDB) – TRANSACTION NOTIFICATION


After a successful transfer, the system sends a notification using JMS (Java Message Service).
Why Message-Driven Bean?
 Enables asynchronous processing
 Ensures transaction durability even if the user logs out

Message-Driven Bean to Process Notifications


import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
Prepared by Dr.K.Sankar Page 4 of 14
import javax.jms.TextMessage;
@MessageDriven(mappedName = "jms/TransactionQueue")
public class NotificationBean implements MessageListener {
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
String notification = ((TextMessage) message).getText();
System.out.println("Transaction Notification: " + notification);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Sending a JMS Notification from Money Transfer Bean


import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSContext;
import javax.jms.Queue;

@Stateless
public class NotificationService {
@Resource(lookup = "jms/ConnectionFactory")
private ConnectionFactory connectionFactory;

@Resource(lookup = "jms/TransactionQueue")
private Queue queue;

public void sendNotification(String message) {


try (JMSContext context = connectionFactory.createContext()) {
context.createProducer().send(queue, message);
}
}
}

6. 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.

Prepared by Dr.K.Sankar Page 5 of 14


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
@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.
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.
Prepared by Dr.K.Sankar Page 6 of 14
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()
{
// 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.
Prepared by Dr.K.Sankar Page 7 of 14
@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.

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.

Prepared by Dr.K.Sankar Page 8 of 14


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.
 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.

Prepared by Dr.K.Sankar Page 9 of 14


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.
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
provided by the Java Persistence API (JPA). It allows developers to perform database queries using object-
Prepared by Dr.K.Sankar Page 10 of 14
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.

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.

Prepared by Dr.K.Sankar Page 11 of 14


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
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(

Prepared by Dr.K.Sankar Page 12 of 14


"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.
 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
Prepared by Dr.K.Sankar Page 13 of 14
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.
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 14 of 14

You might also like