Advanced Java Unit-IV - 2nd Year-Econtent
Advanced Java Unit-IV - 2nd Year-Econtent
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 −
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.
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.
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.
import com.example.ejb.GreetingBean;
import javax.ejb.EJB;
@EJB
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.
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.
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
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.
@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.
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.
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.
import javax.persistence.*;
@Stateless