UNIT 4
UNIT 4
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.
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
@WebServlet("/CheckBalance")
public class AccountServlet extends HttpServlet {
@EJB
private AccountServiceBean accountService;
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;
}
@Stateless
public class NotificationService {
@Resource(lookup = "jms/ConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(lookup = "jms/TransactionQueue")
private Queue queue;
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.
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
@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.
@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.
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.
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.